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
pragma solidity 0.6.5; import "./BaseToken.sol"; import "./Control.sol"; import "./ManagerRole.sol"; import "./OwnerLinkedIdList.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./MinterRole.sol"; contract TokenManager is Control, MinterRole, ManagerRole { using SafeMath for uint256; using Address for address; /*** STORAGE ***/ // All token contract addresses address[] public contracts; // Mapping from contract address to token ID mapping(address => uint256) internal contractToTokenId; // Mapping from contract address to contract issues mapping (address => bool) internal contractIssues; // Mapping from token ID to owner mapping(uint256 => address) internal tokenOwner; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokenIds; // Mapping from holder to token Ids OwnerLinkedIdList private heldTokenIdList; // Mapping from token ID to list of Proxies mapping(uint256 => address[]) internal tokenProxies; // Mapping from token ID to list of Non-Fungible Items mapping(uint256 => uint256[]) internal tokenDistributionPermissions; /*** CONSTRUCTOR ***/ constructor() public { heldTokenIdList = new OwnerLinkedIdList(); } /*** Event ***/ event IssueLog(string _name, string _symbol, uint256 tokenId); event MintLog(address _to, uint256 _value, uint256 tokenId); event TransferLog(address _from, address _to, uint256 _value, uint256 _tokenId); event AddProxyLog(address _proxy, uint256 _tokenId); event AddPermissionLog(uint256 _tokenId, uint256 _specId); /*** EXTERNAL FUNCTIONS ***/ /// @dev issue the specified token in SingulaChain. function issue( address _contractAddress, string memory _name, string memory _symbol ) public whenNotPaused returns (bool) { BaseToken token = BaseToken(_contractAddress); token.issue(_name, _symbol); contracts.push(_contractAddress); uint256 tokenId = contracts.length.sub(1); contractToTokenId[_contractAddress] = tokenId; ownedTokenIds[msg.sender].push(tokenId); tokenOwner[tokenId] = msg.sender; emit IssueLog(_name, _symbol, tokenId); return true; } /// @dev Function to mint tokens /// @param _to The address that will receive the minted tokens. /// @param _value The amount of tokens to mint. /// @param _tokenId token identifer. /// @return A boolean that indicates if the operation was successful. function mint( address _to, uint256 _value, uint256 _tokenId ) public onlyMinter whenNotPaused returns (bool) { require(_exists(_tokenId)); BaseToken token = BaseToken(contracts[_tokenId]); token.mint(_to, _value); _handleTokenHolder(address(0), _to, _tokenId, _value); emit MintLog(_to, _value, _tokenId); return true; } /// @dev Transfer the specified amount of token to the specified address. /// @param _to Receiver address. /// @param _value Amount of tokens that will be transferred. /// @param _tokenId token identifer. function transfer( address _to, uint256 _value, uint256 _tokenId ) public whenNotPaused returns (bool) { require(_exists(_tokenId)); BaseToken token = BaseToken(contracts[_tokenId]); require(_value <= token.balanceOf(msg.sender)); require(_to != address(0)); token.transferFrom(msg.sender, _to, _value); _handleTokenHolder(msg.sender, _to, _tokenId, _value); emit TransferLog(msg.sender, _to, _value, _tokenId); return true; } /// @dev Transfer the specified amount of token from the specified address /// to the specified address. /// @param _from Sender address. /// @param _to Receiver address. /// @param _value Amount of tokens that will be transferred. /// @param _tokenId token identifer. function transferFrom( address _from, address _to, uint256 _value, uint256 _tokenId ) public whenNotPaused returns (bool) { require(_exists(_tokenId)); BaseToken token = BaseToken(contracts[_tokenId]); require(_value <= token.balanceOf(_from)); require(_to != address(0)); token.transferFrom(_from, _to, _value); _handleTokenHolder(_from, _to, _tokenId, _value); emit TransferLog(_from, _to, _value, _tokenId); return true; } /// @dev Transfer the specified amount of token from the specified address /// to the specified address by proxy account. /// @param _from Sender address. /// @param _to Receiver address. /// @param _value Amount of tokens that will be transferred. /// @param _tokenId token identifer. function transferProxy( address _from, address _to, uint256 _value, uint256 _tokenId, uint256 _specId ) public returns (bool) { BaseToken token = BaseToken(contracts[_tokenId]); require(_exists(_tokenId)); require(_value <= token.balanceOf(_from)); require(_to != address(0)); uint256 k = tokenProxies[_tokenId].length; for (uint i = 0; i < k; i++) { if (tokenProxies[_tokenId][i] == msg.sender) { uint256 m = tokenDistributionPermissions[_tokenId].length; for (uint j = 0; j < m; j++) { if (tokenDistributionPermissions[_tokenId][j] == _specId) { token.transferFrom(_from, _to, _value); _handleTokenHolder(_from, _to, _tokenId, _value); emit TransferLog(_from, _to, _value, _tokenId); return true; } } } } return false; } /// @dev Add a proxy account for automatic distribution /// @param _proxy proxy account /// @param _tokenId automatic distribution token function addProxy( address _proxy, uint256 _tokenId ) public returns(bool) { require(tokenOwner[_tokenId] == msg.sender); require(_exists(_tokenId)); tokenProxies[_tokenId].push(_proxy); emit AddProxyLog(_proxy, _tokenId); return true; } /// @dev Add a proxy account for automatic distribution /// @param _specId Digital content spec ID /// @param _tokenId automatic distribution token function addPermission( uint256 _tokenId, uint256 _specId ) public returns(bool) { require(tokenOwner[_tokenId] == msg.sender); require(_exists(_tokenId)); tokenDistributionPermissions[_tokenId].push(_specId); emit AddPermissionLog(_tokenId, _specId); return true; } /// @dev Gets contract count. /// @return count of contract. function getContractCount() public view returns(uint256) { return contracts.length; } /// @dev Gets the contract address of the specified token ID /// @return count of contract. function contractOf(uint256 _tokenId) public view returns(address) { return contracts[_tokenId]; } /// @dev get tokenId from contract address. /// @param _contractAddress Contract address. /// @return count of contract. function getTokenId(address _contractAddress) public view returns(uint256) { require(_exists(_contractAddress)); return contractToTokenId[_contractAddress]; } /// @dev Total number of tokens in existence /// @param _tokenId The token Iidentifer function totalSupplyOf(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId)); BaseToken token = BaseToken(contracts[_tokenId]); return token.totalSupply(); } /// @dev Returns balance of the `_owner`. /// @param _tokenId The token Iidentifer /// @param _owner The address whose balance will be returned. /// @return balance Balance of the `_owner`. function balanceOf(uint256 _tokenId, address _owner) public view returns (uint256) { require(_exists(_tokenId)); BaseToken token = BaseToken(contracts[_tokenId]); return token.balanceOf(_owner); } /// @dev Gets the owner of the specified token ID /// @param _tokenId uint256 ID of the token to query the owner of /// @return holders address currently marked as the owner of the given token ID function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /// @dev Gets the token IDs of the requested owner /// @param _owner address owning the objects list to be accessed /// @return uint256 token IDs owned by the requested address function tokensOfOwner(address _owner) public view returns (uint256[] memory) { return ownedTokenIds[_owner]; } /// @dev Gets the token IDs of the requested owner /// @param _holder address holding the objects list to be accessed /// @return uint256 token IDs held by the requested address function tokensOfHolder(address _holder) public view returns (uint256[] memory) { return heldTokenIdList.valuesOf(_holder); } /// @dev Gets the token object of the specified token ID /// @param _tokenId the tokenId of the token /// @return tokenId the tokenId of the token /// @return contractAddress the contractAddress of the token /// @return name the name of the token /// @return symbol the symbol of the token /// @return owner the owner of the token /// @return totalSupply the total supply of the token function getTokenInfo(uint256 _tokenId) public view returns( uint256 tokenId, address contractAddress, string memory name, string memory symbol, address owner, uint256 totalSupply ) { require(_exists(_tokenId)); BaseToken token = BaseToken(contracts[_tokenId]); return ( _tokenId, contracts[_tokenId], token.nameOf(), token.symbolOf(), ownerOf(_tokenId), token.totalSupply() ); } /// @dev Gets the proxy of the specified token ID /// @param _tokenId uint256 ID of the token to query the proxy of /// @return proxy address list of the given token ID function proxyOf(uint256 _tokenId) public view returns (address[] memory) { return tokenProxies[_tokenId]; } /// @dev Gets the permission of the specified token ID /// @param _tokenId uint256 ID of the token to query the permission of function permissionOf(uint256 _tokenId) public view returns (uint256[] memory) { return tokenDistributionPermissions[_tokenId]; } /*** INTERNAL FUNCTIONS ***/ /// @dev Check if it is issued contract address /// @param _tokenId token id. /// @return A boolean that indicates if the token exists. function _exists(uint256 _tokenId) internal view returns (bool) { if (tokenOwner[_tokenId] != address(0x0)) { return true; } } /// @dev Check if it is issued contract address /// @param _contractAddress token address. /// @return A boolean that indicates if the token exists. function _exists(address _contractAddress) internal view returns (bool) { return contractIssues[_contractAddress]; } /// @dev Internal function to add a token ID to the list of a given address /// @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 _addTokenTo(address _to, uint256 _tokenId) internal { require(!_isRegisteredToken(_tokenId)); ownedTokenIds[_to].push(_tokenId); tokenOwner[_tokenId] = _to; } /// @dev Internal function to add a token ID to the list of a given address /// @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 _addTokenHolderTo(address _to, uint256 _tokenId) internal { require(!_isRegisteredTokenHolder(_to, _tokenId)); // heldTokensIndex[_to][_tokenId] = holderToTokenIds[_to].push(_tokenId); heldTokenIdList.add(_to, _tokenId); } /// @dev Internal function to remove a token ID from the list of a given address /// @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 _removeTokenHolderFrom(address _from, uint256 _tokenId) internal { require(_isRegisteredTokenHolder(_from, _tokenId)); heldTokenIdList.remove(_from, _tokenId); } /// @dev Internal function to handle token holder list /// @param _from address representing the sender /// @param _to address representing the reciever /// @param _tokenId uint256 ID of the token to be handled /// @param _value uint256 amount of token to be handled function _handleTokenHolder(address _from, address _to, uint256 _tokenId, uint256 _value) internal { if (_from != address(0) && BaseToken(contracts[_tokenId]).balanceOf(_from) == 0) { _removeTokenHolderFrom(_from, _tokenId); } if (_to != address(0) && BaseToken(contracts[_tokenId]).balanceOf(_to) == _value) { _addTokenHolderTo(_to, _tokenId); } } /// @dev Returns whether the specified token id registered /// @param _tokenId token identifer. /// @return whether the token registered function _isRegisteredToken(uint256 _tokenId) internal view returns (bool) { return tokenOwner[_tokenId] != address(0); } /// @dev Returns whether the specified token id registered /// @param _to address representing the new owner of the given token ID /// @param _tokenId token identifer. /// @return whether the token registered function _isRegisteredTokenHolder(address _to, uint256 _tokenId) internal view returns (bool) { return heldTokenIdList.exists(_to, _tokenId); } }
** EXTERNAL FUNCTIONS ***/ @dev issue the specified token in SingulaChain.
function issue( address _contractAddress, string memory _name, string memory _symbol ) public whenNotPaused returns (bool) { BaseToken token = BaseToken(_contractAddress); token.issue(_name, _symbol); contracts.push(_contractAddress); uint256 tokenId = contracts.length.sub(1); contractToTokenId[_contractAddress] = tokenId; ownedTokenIds[msg.sender].push(tokenId); tokenOwner[tokenId] = msg.sender; emit IssueLog(_name, _symbol, tokenId); return true; }
12,942,602
[ 1, 2294, 11702, 13690, 55, 342, 225, 5672, 326, 1269, 1147, 316, 348, 310, 5552, 3893, 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 ]
[ 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, 5672, 12, 203, 3639, 1758, 389, 16351, 1887, 16, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 203, 565, 262, 1071, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 203, 3639, 3360, 1345, 1147, 273, 3360, 1345, 24899, 16351, 1887, 1769, 203, 3639, 1147, 18, 13882, 24899, 529, 16, 389, 7175, 1769, 203, 203, 3639, 20092, 18, 6206, 24899, 16351, 1887, 1769, 203, 3639, 2254, 5034, 1147, 548, 273, 20092, 18, 2469, 18, 1717, 12, 21, 1769, 203, 3639, 6835, 774, 1345, 548, 63, 67, 16351, 1887, 65, 273, 1147, 548, 31, 203, 3639, 16199, 1345, 2673, 63, 3576, 18, 15330, 8009, 6206, 12, 2316, 548, 1769, 203, 3639, 1147, 5541, 63, 2316, 548, 65, 273, 1234, 18, 15330, 31, 203, 203, 203, 3639, 3626, 11820, 1343, 24899, 529, 16, 389, 7175, 16, 1147, 548, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6c0B6cDBf6e1910CD5821440872a6C6145526658/sources/contracts/BaseBridge.sol
Increment the total released counter.
totalReleased += userBalance;
8,288,492
[ 1, 10798, 326, 2078, 15976, 3895, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 26363, 1011, 729, 13937, 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 ]
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/nftMarket/NFTMarketExhibition.sol
* @notice Emitted when an NFT is no longer associated with an exhibition for reasons other than a sale. @param nftContract The contract address of the NFT. @param tokenId The ID of the NFT. @param exhibitionId The ID of the exhibition it was originally listed with./
event NftRemovedFromExhibition(address indexed nftContract, uint256 indexed tokenId, uint256 indexed exhibitionId);
8,357,051
[ 1, 1514, 11541, 1347, 392, 423, 4464, 353, 1158, 7144, 3627, 598, 392, 431, 15769, 608, 364, 14000, 1308, 2353, 279, 272, 5349, 18, 225, 290, 1222, 8924, 1021, 6835, 1758, 434, 326, 423, 4464, 18, 225, 1147, 548, 1021, 1599, 434, 326, 423, 4464, 18, 225, 431, 15769, 608, 548, 1021, 1599, 434, 326, 431, 15769, 608, 518, 1703, 24000, 12889, 598, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 871, 423, 1222, 10026, 1265, 424, 15769, 608, 12, 2867, 8808, 290, 1222, 8924, 16, 2254, 5034, 8808, 1147, 548, 16, 2254, 5034, 8808, 431, 15769, 608, 548, 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 ]
./partial_match/1313161554/0x27Bc45c2A25f57CbE59FeB829BeEe26Bd97726aB/sources/PLYStrategy.sol
@notice Shows amount of collected reward calculated in ETH. @return Amount of collected reward in ETH.
function rewardsInEth() external view override returns (uint256) { uint256 earnedReward = wantRewardCollected; address comp = IAuERC20(auToken).comptroller(); earnedReward += IComptrollerAurigami(comp).rewardAccrued(REWARD_TYPE_PLY, address(this)); earnedReward += IPULP(pulp).getMaxAmountRedeemable(address(this)); if (earnedReward > DUST_AMOUNT) { return _rewardsInEth(earnedReward); } return 0; }
16,926,644
[ 1, 24548, 3844, 434, 12230, 19890, 8894, 316, 512, 2455, 18, 327, 16811, 434, 12230, 19890, 316, 512, 2455, 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 ]
[ 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, 283, 6397, 382, 41, 451, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 425, 1303, 329, 17631, 1060, 273, 2545, 17631, 1060, 10808, 329, 31, 203, 3639, 1758, 1161, 273, 467, 37, 89, 654, 39, 3462, 12, 8377, 1345, 2934, 832, 337, 1539, 5621, 203, 3639, 425, 1303, 329, 17631, 1060, 1011, 467, 799, 337, 1539, 37, 295, 360, 26223, 12, 2919, 2934, 266, 2913, 8973, 86, 5957, 12, 862, 21343, 67, 2399, 67, 23893, 16, 1758, 12, 2211, 10019, 203, 3639, 425, 1303, 329, 17631, 1060, 1011, 2971, 1506, 52, 12, 84, 14290, 2934, 588, 2747, 6275, 426, 24903, 429, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 73, 1303, 329, 17631, 1060, 405, 463, 5996, 67, 2192, 51, 5321, 13, 288, 203, 5411, 327, 389, 266, 6397, 382, 41, 451, 12, 73, 1303, 329, 17631, 1060, 1769, 203, 3639, 289, 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 ]
./partial_match/1/0x5fa60726E62c50Af45Ff2F6280C468DA438A7837/sources/contracts/exchangeV2/BlurExchangeV2.sol
* @notice Wrapper of _takeAskSingle that verifies an oracle signature of the calldata before executing @param inputs Inputs for _takeAskSingle @param oracleSignature Oracle signature of inputs/
function takeAskSingle( TakeAskSingle memory inputs, bytes calldata oracleSignature ) public payable nonReentrant verifyOracleSignature(_hashCalldata(msg.sender), oracleSignature) { _takeAskSingle( inputs.order, inputs.exchange, inputs.takerFee, inputs.signature, inputs.tokenRecipient ); }
4,003,411
[ 1, 3611, 434, 389, 22188, 23663, 5281, 716, 20761, 392, 20865, 3372, 434, 326, 745, 892, 1865, 11274, 225, 4540, 24472, 364, 389, 22188, 23663, 5281, 225, 20865, 5374, 28544, 3372, 434, 4540, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4862, 23663, 5281, 12, 203, 3639, 17129, 23663, 5281, 3778, 4540, 16, 203, 3639, 1731, 745, 892, 20865, 5374, 203, 565, 262, 203, 3639, 1071, 203, 3639, 8843, 429, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 3929, 23601, 5374, 24899, 2816, 1477, 892, 12, 3576, 18, 15330, 3631, 20865, 5374, 13, 203, 565, 288, 203, 3639, 389, 22188, 23663, 5281, 12, 203, 5411, 4540, 18, 1019, 16, 203, 5411, 4540, 18, 16641, 16, 203, 5411, 4540, 18, 88, 6388, 14667, 16, 203, 5411, 4540, 18, 8195, 16, 203, 5411, 4540, 18, 2316, 18241, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x22B475f3e93390b7E523873ad7073337f4E56C2c/sources/EFIL.sol
* @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 transferable(recipient, _msgSender()) override returns (bool) { checkNewHolder(recipient); bool res = super.transfer(recipient, amount); address account = _msgSender(); checkOldHolder(account); return res; }
2,895,019
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 13866, 5496, 29076, 30, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 326, 4894, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 7412, 429, 12, 20367, 16, 389, 3576, 12021, 10756, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 866, 1908, 6064, 12, 20367, 1769, 203, 3639, 1426, 400, 273, 2240, 18, 13866, 12, 20367, 16, 3844, 1769, 203, 3639, 1758, 2236, 273, 389, 3576, 12021, 5621, 203, 3639, 866, 7617, 6064, 12, 4631, 1769, 203, 3639, 327, 400, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-20 */ // File: @openzeppelin/contracts/utils/math/SafeMath.sol // 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; } } } pragma solidity 0.8.0; interface IStaking { function getEpochId(uint timestamp) external view returns (uint); // get epoch id function getEpochUserBalance(address user, address token, uint128 epoch) external view returns(uint); function getEpochPoolSize(address token, uint128 epoch) external view returns (uint); function epoch1Start() external view returns (uint); function epochDuration() external view returns (uint); function hasReferrer(address addr) external view returns(bool); function referrals(address addr) external view returns(address); function firstReferrerRewardPercentage() external view returns(uint256); function secondReferrerRewardPercentage() external view returns(uint256); function isStakeFinished(address staker) external view returns (bool); function stakeData(address staker) external view returns (uint256 startEpoch, uint256 endEpoch, bool active); function stakeEndEpoch(address staker) external view returns (uint128); function calcDurationBonusMultiplier(uint128 epochId, address staker) external view returns (uint256); } interface Minter { function mint(address to, uint256 amount) external; } contract SwappYieldFarm { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant NR_OF_EPOCHS = 60; uint256 constant private CALC_MULTIPLIER = 1000000; // addreses address private _swappAddress = 0x8CB924583681cbFE487A62140a994A49F833c244; address private _owner; bool private _paused = false; // contracts IStaking private _staking; Minter private _minter; uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); uint128 public lastInitializedEpoch; mapping(address => uint128) public lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract mapping(uint128 => uint256) public epochAmounts; mapping(uint128 => uint256) public epochDurationBonus; mapping(address => uint256) public collectedDurationBonus; modifier onlyStaking() { require(msg.sender == address(_staking), "Only staking contract can perfrom this action"); _; } modifier onlyOwner() { require(msg.sender == _owner, "Only owner can perfrom this action"); _; } modifier whenNotPaused() { require(!paused(), "Contract is paused"); _; } // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); event ReferrerRewardCollected(address indexed staker, address indexed referrer, uint256 rewardAmount); event Referrer2RewardCollected(address indexed staker, address indexed referrer, address indexed referrer2, uint256 rewardAmount); event DurationBonusCollected(address indexed staker, uint128 indexed epochId, uint256 bonusAmount); event DurationBonusDistributed(address indexed staker, uint128 indexed epochId, uint256 bonusAmount); event DurationBonusLost(address indexed staker, uint128 indexed epochId, uint256 bonusAmount); // constructor constructor() { _staking = IStaking(0x60F4D3e409Ad2Bb6BF5edFBCC85691eE1977cf35); _minter = Minter(0xBC1f9993ea5eE2C77909bf43d7a960bB8dA8C9B9); epochDuration = _staking.epochDuration(); epochStart = _staking.epoch1Start(); _owner = msg.sender; _initEpochReward(); _initDurationBonus(); } function setEpochAmount(uint128 epochId, uint256 amount) external onlyOwner { require(epochId > 0 && epochId <= NR_OF_EPOCHS, "Minimum epoch number is 1 and Maximum number of epochs is 60"); require(epochId > _getEpochId(), "Only future epoch can be updated"); epochAmounts[epochId] = amount; } function setEpochDurationBonus(uint128 epochId, uint256 amount) external onlyOwner { require(epochId > 0 && epochId <= NR_OF_EPOCHS, "Minimum epoch number is 1 and Maximum number of epochs is 60"); require(epochId > _getEpochId(), "Only future epoch can be updated"); epochDurationBonus[epochId] = amount; } function getTotalAmountPerEpoch(uint128 epoch) public view returns (uint) { return epochAmounts[epoch].mul(10**18); } function getDurationBonusPerEpoch(uint128 epoch) public view returns (uint) { return epochDurationBonus[epoch].mul(10**18); } function getCurrentEpochAmount() public view returns (uint) { uint128 currentEpoch = _getEpochId(); if (currentEpoch <= 0 || currentEpoch > NR_OF_EPOCHS) { return 0; } return epochAmounts[currentEpoch]; } function getCurrentEpochDurationBonus() public view returns (uint) { uint128 currentEpoch = _getEpochId(); if (currentEpoch <= 0 || currentEpoch > NR_OF_EPOCHS) { return 0; } return epochDurationBonus[currentEpoch]; } function getTotalDistributedAmount() external view returns(uint256) { uint256 totalDistributed; for (uint128 i = 1; i <= NR_OF_EPOCHS; i++) { totalDistributed += epochAmounts[i]; } return totalDistributed; } function getTotalDurationBonus() external view returns(uint256) { uint256 totalBonus; for (uint128 i = 1; i <= NR_OF_EPOCHS; i++) { totalBonus += epochDurationBonus[i]; } return totalBonus; } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external whenNotPaused returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); uint256 durationBonus = _calcDurationBonus(i); if (durationBonus > 0) { collectedDurationBonus[msg.sender] = collectedDurationBonus[msg.sender].add(durationBonus); emit DurationBonusCollected(msg.sender, i, durationBonus); } } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); uint256 totalDurationBonus = 0; if (_staking.isStakeFinished(msg.sender) && collectedDurationBonus[msg.sender] > 0) { totalDurationBonus = collectedDurationBonus[msg.sender]; collectedDurationBonus[msg.sender] = 0; _minter.mint(msg.sender, totalDurationBonus); emit DurationBonusDistributed(msg.sender, _getEpochId(), totalDurationBonus); } if (totalDistributedValue > 0) { _minter.mint(msg.sender, totalDistributedValue); //Referrer reward distributeReferrerReward(totalDistributedValue.add(totalDurationBonus)); } return totalDistributedValue.add(totalDurationBonus); } function harvest (uint128 epochId) external whenNotPaused returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 60"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); uint256 durationBonus = _calcDurationBonus(epochId); collectedDurationBonus[msg.sender] = collectedDurationBonus[msg.sender].add(_calcDurationBonus(epochId)); emit DurationBonusCollected(msg.sender, epochId, durationBonus); uint256 totalDurationBonus = 0; if (_staking.isStakeFinished(msg.sender) && collectedDurationBonus[msg.sender] > 0) { totalDurationBonus = collectedDurationBonus[msg.sender]; collectedDurationBonus[msg.sender] = 0; _minter.mint(msg.sender, totalDurationBonus); emit DurationBonusDistributed(msg.sender, epochId, totalDurationBonus); } if (userReward > 0) { _minter.mint(msg.sender, userReward); //Referrer reward distributeReferrerReward(userReward.add(totalDurationBonus)); } emit Harvest(msg.sender, epochId, userReward); return userReward.add(totalDurationBonus); } function distributeReferrerReward(uint256 stakerReward) internal { if (_staking.hasReferrer(msg.sender)) { address referrer = _staking.referrals(msg.sender); uint256 ref1Reward = stakerReward.mul(_staking.firstReferrerRewardPercentage()).div(10000); _minter.mint(referrer, ref1Reward); emit ReferrerRewardCollected(msg.sender, referrer, ref1Reward); // second step referrer if (_staking.hasReferrer(referrer)) { address referrer2 = _staking.referrals(referrer); uint256 ref2Reward = stakerReward.mul(_staking.secondReferrerRewardPercentage()).div(10000); _minter.mint(referrer2, ref2Reward); emit Referrer2RewardCollected(msg.sender, referrer, referrer2, ref2Reward); } } } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } function getUserLastEpochHarvested(address staker) external view returns (uint) { return lastEpochIdHarvested[staker]; } function estimateDurationBonus (uint128 epochId) public view returns (uint) { uint256 poolSize = _getPoolSize(epochId); // exit if there is no stake on the epoch if (poolSize == 0) { return 0; } uint256 stakerMultiplier = stakerDurationMultiplier(msg.sender, epochId + 1); return getDurationBonusPerEpoch(epochId) .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(poolSize).mul(stakerMultiplier).div(CALC_MULTIPLIER); } function stakerDurationMultiplier(address staker, uint128 epochId) public view returns (uint256) { (uint256 startEpoch, uint256 endEpoch, bool active) = _staking.stakeData(staker); if (epochId > endEpoch || (epochId <= endEpoch && active == false) || epochId < startEpoch) { return 0; } uint256 stakerMultiplier = _staking.calcDurationBonusMultiplier(epochId, staker); return stakerMultiplier; } function reduceDurationBonus(address staker, uint256 reduceMultiplier) public onlyStaking { uint256 collected = collectedDurationBonus[staker]; if (collected > 0) { collectedDurationBonus[staker] = collected.mul(reduceMultiplier).div(CALC_MULTIPLIER); uint256 bonusLost = collected.sub(collectedDurationBonus[staker]); DurationBonusLost(staker, _getEpochId(), bonusLost); } } function clearDurationBonus(address staker) public onlyStaking { uint256 collected = collectedDurationBonus[staker]; if (collected > 0) { collectedDurationBonus[staker] = 0; DurationBonusLost(staker, _getEpochId(), collected); } } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails // if it fails either user either a Swapp account will init not init epochs if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user state for last harvested lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } uint128 endEpoch = _staking.stakeEndEpoch(msg.sender); if (epochId >= endEpoch) { return 0; } return getTotalAmountPerEpoch(epochId) .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } function _calcDurationBonus(uint128 epochId) internal view returns (uint) { // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } uint256 stakerMultiplier = stakerDurationMultiplier(msg.sender, epochId + 1); return getDurationBonusPerEpoch(epochId) .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]).mul(stakerMultiplier).div(CALC_MULTIPLIER); } function _getPoolSize(uint128 epochId) internal view returns (uint) { // retrieve token balance return _staking.getEpochPoolSize(_swappAddress, epochId); } function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ // retrieve token balance per user per epoch return _staking.getEpochUserBalance(userAddress, _swappAddress, epochId); } // compute epoch id from blocktimestamp and epochstart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } function paused() public view returns (bool) { return _paused; } function pause() external onlyOwner { _paused = true; } function unpause() external onlyOwner { _paused = false; } function _initEpochReward() internal { epochAmounts[1] = 5000000; epochAmounts[2] = 2000000; epochAmounts[3] = 2000000; epochAmounts[4] = 2000000; epochAmounts[5] = 2000000; epochAmounts[6] = 2000000; epochAmounts[7] = 1500000; epochAmounts[8] = 1500000; epochAmounts[9] = 1500000; epochAmounts[10] = 1500000; epochAmounts[11] = 1500000; epochAmounts[12] = 1500000; epochAmounts[13] = 500000; epochAmounts[14] = 500000; epochAmounts[15] = 500000; epochAmounts[16] = 500000; epochAmounts[17] = 500000; epochAmounts[18] = 500000; epochAmounts[19] = 500000; epochAmounts[20] = 500000; epochAmounts[21] = 500000; epochAmounts[22] = 500000; epochAmounts[23] = 500000; epochAmounts[24] = 500000; epochAmounts[25] = 400000; epochAmounts[26] = 400000; epochAmounts[27] = 400000; epochAmounts[28] = 400000; epochAmounts[29] = 400000; epochAmounts[30] = 400000; epochAmounts[31] = 400000; epochAmounts[32] = 400000; epochAmounts[33] = 400000; epochAmounts[34] = 400000; epochAmounts[35] = 400000; epochAmounts[36] = 400000; epochAmounts[37] = 250000; epochAmounts[38] = 250000; epochAmounts[39] = 250000; epochAmounts[40] = 250000; epochAmounts[41] = 250000; epochAmounts[42] = 250000; epochAmounts[43] = 250000; epochAmounts[44] = 250000; epochAmounts[45] = 250000; epochAmounts[46] = 250000; epochAmounts[47] = 250000; epochAmounts[48] = 250000; epochAmounts[49] = 250000; epochAmounts[50] = 250000; epochAmounts[51] = 250000; epochAmounts[52] = 250000; epochAmounts[53] = 250000; epochAmounts[54] = 250000; epochAmounts[55] = 250000; epochAmounts[56] = 250000; epochAmounts[57] = 250000; epochAmounts[58] = 250000; epochAmounts[59] = 250000; epochAmounts[60] = 250000; } function _initDurationBonus() internal { epochDurationBonus[1] = 21450; epochDurationBonus[2] = 23595; epochDurationBonus[3] = 25954; epochDurationBonus[4] = 28550; epochDurationBonus[5] = 31405; epochDurationBonus[6] = 34545; epochDurationBonus[7] = 38000; epochDurationBonus[8] = 41800; epochDurationBonus[9] = 45980; epochDurationBonus[10] = 50578; epochDurationBonus[11] = 55635; epochDurationBonus[12] = 61477; epochDurationBonus[13] = 67932; epochDurationBonus[14] = 75065; epochDurationBonus[15] = 82947; epochDurationBonus[16] = 91656; epochDurationBonus[17] = 101280; epochDurationBonus[18] = 111915; epochDurationBonus[19] = 123666; epochDurationBonus[20] = 136651; epochDurationBonus[21] = 150999; epochDurationBonus[22] = 166854; epochDurationBonus[23] = 184374; epochDurationBonus[24] = 204701; epochDurationBonus[25] = 227269; epochDurationBonus[26] = 252326; epochDurationBonus[27] = 280145; epochDurationBonus[28] = 311031; epochDurationBonus[29] = 345322; epochDurationBonus[30] = 383393; epochDurationBonus[31] = 425662; epochDurationBonus[32] = 472592; epochDurationBonus[33] = 524695; epochDurationBonus[34] = 582543; epochDurationBonus[35] = 646768; epochDurationBonus[36] = 721639; epochDurationBonus[37] = 805178; epochDurationBonus[38] = 898388; epochDurationBonus[39] = 1002387; epochDurationBonus[40] = 1118426; epochDurationBonus[41] = 1247898; epochDurationBonus[42] = 1392358; epochDurationBonus[43] = 1553541; epochDurationBonus[44] = 1733382; epochDurationBonus[45] = 1934043; epochDurationBonus[46] = 2157933; epochDurationBonus[47] = 2407740; epochDurationBonus[48] = 2700403; epochDurationBonus[49] = 3028638; epochDurationBonus[50] = 3396771; epochDurationBonus[51] = 3809651; epochDurationBonus[52] = 4272716; epochDurationBonus[53] = 4792068; epochDurationBonus[54] = 5374546; epochDurationBonus[55] = 6027826; epochDurationBonus[56] = 6760512; epochDurationBonus[57] = 7582256; epochDurationBonus[58] = 8503884; epochDurationBonus[59] = 9537537; epochDurationBonus[60] = 11000000; } }
try to initialize an epoch. if it can't it fails if it fails either user either a Swapp account will init not init epochs exit if there is no stake on the epoch
function _harvest (uint128 epochId) internal returns (uint) { if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } if (epochs[epochId] == 0) { return 0; } uint128 endEpoch = _staking.stakeEndEpoch(msg.sender); if (epochId >= endEpoch) { return 0; } return getTotalAmountPerEpoch(epochId) .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); }
10,991,878
[ 1, 698, 358, 4046, 392, 7632, 18, 309, 518, 848, 1404, 518, 6684, 309, 518, 6684, 3344, 729, 3344, 279, 5434, 2910, 2236, 903, 1208, 486, 1208, 25480, 2427, 309, 1915, 353, 1158, 384, 911, 603, 326, 7632, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 389, 30250, 26923, 261, 11890, 10392, 7632, 548, 13, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 309, 261, 2722, 11459, 14638, 411, 7632, 548, 13, 288, 203, 5411, 389, 2738, 14638, 12, 12015, 548, 1769, 203, 3639, 289, 203, 3639, 309, 261, 28530, 63, 12015, 548, 65, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 540, 203, 3639, 2254, 10392, 679, 14638, 273, 389, 334, 6159, 18, 334, 911, 1638, 14638, 12, 3576, 18, 15330, 1769, 203, 3639, 309, 261, 12015, 548, 1545, 679, 14638, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 540, 203, 3639, 327, 12831, 6275, 2173, 14638, 12, 12015, 548, 13, 203, 3639, 263, 16411, 24899, 588, 1299, 13937, 2173, 14638, 12, 3576, 18, 15330, 16, 7632, 548, 3719, 203, 3639, 263, 2892, 12, 28530, 63, 12015, 548, 19226, 203, 565, 289, 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 ]
./full_match/3/0x6bbB36f3De94869178160d8eF765Eb6f4736c4E9/sources/browser/solo_miner.sol
-----------EXTERNAL----------------
function mine(uint depositAmount) isActive external virtual returns(bool success) { require(depositAmount > 0, "at: solo_miner.sol | contract: SoloMiner | function: mine | message: No zero deposits allowed"); uint gapSize = getGapSize(); uint reward = showMyCurrentRewardTotal(); reward = reward.add(depositAmount); burn(depositAmount); gapSize = getGapSize(); numerator[msg.sender] = reward; denominator[msg.sender] = gapSize; minimumReturn[msg.sender] = minimumReturn[msg.sender].add(depositAmount); userBlocks[msg.sender] = getCurrentBlockNumber(); return true; }
8,209,735
[ 1, 13849, 2294, 11702, 1271, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 282, 445, 312, 558, 12, 11890, 443, 1724, 6275, 13, 15083, 3903, 5024, 1135, 12, 6430, 2216, 13, 288, 203, 1377, 203, 377, 2583, 12, 323, 1724, 6275, 405, 374, 16, 203, 377, 315, 270, 30, 3704, 83, 67, 1154, 264, 18, 18281, 571, 6835, 30, 348, 12854, 2930, 264, 571, 445, 30, 312, 558, 571, 883, 30, 2631, 3634, 443, 917, 1282, 2935, 8863, 203, 1377, 203, 1377, 203, 377, 2254, 9300, 1225, 273, 7162, 438, 1225, 5621, 203, 377, 2254, 19890, 273, 2405, 12062, 3935, 17631, 1060, 5269, 5621, 203, 377, 19890, 273, 19890, 18, 1289, 12, 323, 1724, 6275, 1769, 203, 203, 377, 18305, 12, 323, 1724, 6275, 1769, 203, 1377, 203, 377, 9300, 1225, 273, 7162, 438, 1225, 5621, 203, 1377, 203, 377, 16730, 63, 3576, 18, 15330, 65, 273, 19890, 31, 203, 377, 15030, 63, 3576, 18, 15330, 65, 273, 9300, 1225, 31, 203, 377, 5224, 990, 63, 3576, 18, 15330, 65, 273, 5224, 990, 63, 3576, 18, 15330, 8009, 1289, 12, 323, 1724, 6275, 1769, 203, 377, 729, 6450, 63, 3576, 18, 15330, 65, 273, 5175, 1768, 1854, 5621, 203, 1377, 203, 377, 327, 638, 31, 203, 282, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-08 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.6; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } 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; } } contract Owned is Context { modifier onlyOwner() virtual{ require(_msgSender()==owner); _; } address payable owner; address payable newOwner; function changeOwner(address payable _newOwner) external onlyOwner { require(_newOwner!=address(0)); newOwner = _newOwner; } function acceptOwnership() external { if (_msgSender()==newOwner) { owner = newOwner; } } } interface ERC20 { function balanceOf(address _owner) view external returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) view external returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract PIKA is Context,Owned, ERC20 { using SafeMath for uint256; uint256 public _taxFee; uint256 public totalSupply; string public symbol; string public name; uint8 public decimals; uint256 private _taxFeepercent = 225; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) private _isExcludedFromFee; uint256 public ContractDeployed; address oldPika = 0xE09fB60E8D6e7E1CEbBE821bD5c3FC67a40F86bF; uint256 public oldPika_amount; uint256 private minamountTakenOut = 1000000 *10**9 * 10 **9; uint256 private MinimumSupply = 100000000 *10**9 * 10**9; mapping (address=>uint256) balances; mapping (address=>mapping (address=>uint256)) allowed; event TransferFee(address indexed _from, address indexed _to, uint256 _value); function balanceOf(address _owner) view public override returns (uint256 balance) {return balances[_owner];} function transfer(address _to, uint256 _amount) public override returns (bool success) { _transfer(_msgSender(), _to, _amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool success) { _transfer(sender, recipient, amount); uint256 currentAllowance = allowed[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) { uint256 senderBalance = balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); balances[sender] = senderBalance - amount; balances[recipient] += amount; emit Transfer(sender, recipient, amount); } else { uint256 _Fee = calSwapToken(amount,_taxFeepercent); _taxFee += _Fee; if(_taxFee >= minamountTakenOut ) { swapTokensForEth(_taxFee); } uint256 senderBalance = balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); balances[sender] = senderBalance - amount; balances[recipient] += amount-_Fee ; emit Transfer(sender, recipient, amount-_Fee); } } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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"); allowed[owner][spender] = amount; emit Approval(owner, spender, amount); } function allowance(address _owner, address _spender) view public override returns (uint256 remaining) { return allowed[_owner][_spender]; } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); uint256 accountBalance = balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); balances[account] = accountBalance - amount; totalSupply -= amount; emit Transfer(account, address(0), amount); } 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, owner, block.timestamp ); _taxFee =0; } function viewMinExtractAmt() public view returns(uint256){ return minamountTakenOut; } function setMinExtractAmt(uint256 _amount) public onlyOwner() { minamountTakenOut = _amount; } function viewFee() public view returns(uint256){ return _taxFeepercent ; } function exchnagePika(uint256 tokens)external{ require(tokens <= PIKA(address(this)).balanceOf(address(this)), "Not enough tokens in the reserve"); require(ERC20(oldPika).transferFrom(_msgSender(), address(this), tokens), "Tokens cannot be transferred from user account"); uint256 time = block.timestamp - ContractDeployed; uint256 day = time.div(86400); require(day <= 4, "Sorry Swaping Time Period is finished"); if(tokens < 10000000000 * 10**9 * 10**9) { uint256 extra = calSwapToken(tokens,500); PIKA(address(this)).transfer(_msgSender(), tokens.add(extra)); } else if ( (tokens >= 10000000000 * 10**9 * 10**9) && (tokens < 100000000000 * 10**9 * 10**9)) { uint256 extra = calSwapToken(tokens,250); PIKA(address(this)).transfer(_msgSender(), tokens.add(extra)); } else if( tokens >= 100000000000 * 10**9 * 10**9 ) { uint256 extra = calSwapToken(tokens,100); PIKA(address(this)).transfer(_msgSender(), tokens.add(extra)); } oldPika_amount = oldPika_amount.add(tokens); } function extractOldPIKA() external onlyOwner(){ ERC20(oldPika).transfer(_msgSender(), oldPika_amount); oldPika_amount = 0; } function extractfee() external onlyOwner(){ PIKA(address(this)).transfer(_msgSender(), _taxFee); _taxFee = 0; } function calSwapToken(uint256 _tokens, uint256 cust) internal virtual returns (uint256) { uint256 custPercentofTokens = _tokens.mul(cust).div(100 * 10**uint(2)); return custPercentofTokens; } function burn(uint256 value) public returns(bool flag) { if(totalSupply >= MinimumSupply) { _burn(_msgSender(), value); return true; } else return false; } function viewMinSupply()public view returns(uint256) { return MinimumSupply; } function changeMinSupply(uint256 newMinSupply)onlyOwner() public{ MinimumSupply = newMinSupply; } function addLiquidity(uint256 tokenAmount) public payable onlyOwner() { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: msg.value}( address(this), tokenAmount, 0, 0, // slippage is unavoidable owner, block.timestamp ); } constructor() { symbol = "PIKA"; name = "PIKA"; decimals = 18; totalSupply = 50000000000000 * 10**9 * 10**9; //50 trillion owner = _msgSender(); balances[owner] = totalSupply; _isExcludedFromFee[owner] = true; _isExcludedFromFee[address(this)] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; ContractDeployed = block.timestamp; } receive () payable external { require(msg.value>0); owner.transfer(msg.value); } }
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
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; }
7,752,486
[ 1, 27998, 14850, 30, 333, 353, 19315, 7294, 2353, 29468, 296, 69, 11, 486, 3832, 3634, 16, 1496, 326, 27641, 7216, 353, 13557, 309, 296, 70, 11, 353, 2546, 18432, 18, 2164, 30, 2333, 30, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 13469, 19, 25, 3787, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 4202, 309, 261, 69, 422, 374, 13, 288, 203, 6647, 327, 374, 31, 203, 4202, 289, 203, 203, 4202, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 4202, 2583, 12, 71, 342, 279, 422, 324, 16, 315, 9890, 10477, 30, 23066, 9391, 8863, 203, 203, 4202, 327, 276, 31, 203, 282, 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 ]
//Address: 0x0f33bb20a282a7649c7b3aff644f084a9348e933 //Contract name: YupieToken //Balance: 0.075682742538039924 Ether //Verification Date: 8/15/2017 //Transacion Count: 1600 // CODE STARTS HERE pragma solidity ^0.4.11; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) returns (bool) { 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) 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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _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[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract YupieToken is StandardToken { using SafeMath for uint256; // EVENTS event CreatedYUPIE(address indexed _creator, uint256 _amountOfYUPIE); // TOKEN DATA string public constant name = "YUPIE"; string public constant symbol = "YUP"; uint256 public constant decimals = 18; string public version = "1.0"; // YUPIE TOKEN PURCHASE LIMITS uint256 public maxPresaleSupply; // MAX TOTAL DURING PRESALE (0.8% of MAXTOTALSUPPLY) // PURCHASE DATES uint256 public constant preSaleStartTime = 1502784000; // GMT: Tuesday, August 15, 2017 8:00:00 AM uint256 public constant preSaleEndTime = 1505671200; // GMT: Sunday, September 17, 2017 6:00:00 PM uint256 public saleStartTime = 1509523200; // GMT: Wednesday, November 1, 2017 8:00:00 AM uint256 public saleEndTime = 1512115200; // GMT: Friday, December 1, 2017 8:00:00 AM // PURCHASE BONUSES uint256 public lowEtherBonusLimit = 5 * 1 ether; // 5+ Ether uint256 public lowEtherBonusValue = 110; // 10% Discount uint256 public midEtherBonusLimit = 24 * 1 ether; // 24+ Ether uint256 public midEtherBonusValue = 115; // 15% Discount uint256 public highEtherBonusLimit = 50 * 1 ether; // 50+ Ether uint256 public highEtherBonusValue = 120; // 20% Discount uint256 public highTimeBonusLimit = 0; // 1-12 Days uint256 public highTimeBonusValue = 120; // 20% Discount uint256 public midTimeBonusLimit = 1036800; // 12-24 Days uint256 public midTimeBonusValue = 115; // 15% Discount uint256 public lowTimeBonusLimit = 2073600; // 24+ Days uint256 public lowTimeBonusValue = 110; // 10% Discount // PRICING INFO uint256 public constant YUPIE_PER_ETH_PRE_SALE = 3000; // 3000 YUPIE = 1 ETH uint256 public constant YUPIE_PER_ETH_SALE = 1000; // 1000 YUPIE = 1 ETH // ADDRESSES address public constant ownerAddress = 0x20C84e76C691e38E81EaE5BA60F655b8C388718D; // The owners address // STATE INFO bool public allowInvestment = true; // Flag to change if transfering is allowed uint256 public totalWEIInvested = 0; // Total WEI invested uint256 public totalYUPIESAllocated = 0; // Total YUPIES allocated mapping (address => uint256) public WEIContributed; // Total WEI Per Account // INITIALIZATIONS FUNCTION function YupieToken() { require(msg.sender == ownerAddress); totalSupply = 631*1000000*1000000000000000000; // MAX TOTAL YUPIES 631 million uint256 totalYUPIESReserved = totalSupply.mul(55).div(100); // 55% reserved for Crowdholding maxPresaleSupply = totalSupply*8/1000 + totalYUPIESReserved; // MAX TOTAL DURING PRESALE (0.8% of MAXTOTALSUPPLY) balances[msg.sender] = totalYUPIESReserved; totalYUPIESAllocated = totalYUPIESReserved; } // FALL BACK FUNCTION TO ALLOW ETHER DONATIONS function() payable { require(allowInvestment); // Smallest investment is 0.00001 ether uint256 amountOfWei = msg.value; require(amountOfWei >= 10000000000000); uint256 amountOfYUPIE = 0; uint256 absLowTimeBonusLimit = 0; uint256 absMidTimeBonusLimit = 0; uint256 absHighTimeBonusLimit = 0; uint256 totalYUPIEAvailable = 0; // Investment periods if (block.timestamp > preSaleStartTime && block.timestamp < preSaleEndTime) { // Pre-sale ICO amountOfYUPIE = amountOfWei.mul(YUPIE_PER_ETH_PRE_SALE); absLowTimeBonusLimit = preSaleStartTime + lowTimeBonusLimit; absMidTimeBonusLimit = preSaleStartTime + midTimeBonusLimit; absHighTimeBonusLimit = preSaleStartTime + highTimeBonusLimit; totalYUPIEAvailable = maxPresaleSupply - totalYUPIESAllocated; } else if (block.timestamp > saleStartTime && block.timestamp < saleEndTime) { // ICO amountOfYUPIE = amountOfWei.mul(YUPIE_PER_ETH_SALE); absLowTimeBonusLimit = saleStartTime + lowTimeBonusLimit; absMidTimeBonusLimit = saleStartTime + midTimeBonusLimit; absHighTimeBonusLimit = saleStartTime + highTimeBonusLimit; totalYUPIEAvailable = totalSupply - totalYUPIESAllocated; } else { // Invalid investment period revert(); } // Check that YUPIES calculated greater than zero assert(amountOfYUPIE > 0); // Apply Bonuses if (amountOfWei >= highEtherBonusLimit) { amountOfYUPIE = amountOfYUPIE.mul(highEtherBonusValue).div(100); } else if (amountOfWei >= midEtherBonusLimit) { amountOfYUPIE = amountOfYUPIE.mul(midEtherBonusValue).div(100); } else if (amountOfWei >= lowEtherBonusLimit) { amountOfYUPIE = amountOfYUPIE.mul(lowEtherBonusValue).div(100); } if (block.timestamp >= absLowTimeBonusLimit) { amountOfYUPIE = amountOfYUPIE.mul(lowTimeBonusValue).div(100); } else if (block.timestamp >= absMidTimeBonusLimit) { amountOfYUPIE = amountOfYUPIE.mul(midTimeBonusValue).div(100); } else if (block.timestamp >= absHighTimeBonusLimit) { amountOfYUPIE = amountOfYUPIE.mul(highTimeBonusValue).div(100); } // Max sure it doesn't exceed remaining supply assert(amountOfYUPIE <= totalYUPIEAvailable); // Update total YUPIE balance totalYUPIESAllocated = totalYUPIESAllocated + amountOfYUPIE; // Update user YUPIE balance uint256 balanceSafe = balances[msg.sender].add(amountOfYUPIE); balances[msg.sender] = balanceSafe; // Update total WEI Invested totalWEIInvested = totalWEIInvested.add(amountOfWei); // Update total WEI Invested by account uint256 contributedSafe = WEIContributed[msg.sender].add(amountOfWei); WEIContributed[msg.sender] = contributedSafe; // CHECK VALUES assert(totalYUPIESAllocated <= totalSupply); assert(totalYUPIESAllocated > 0); assert(balanceSafe > 0); assert(totalWEIInvested > 0); assert(contributedSafe > 0); // CREATE EVENT FOR SENDER CreatedYUPIE(msg.sender, amountOfYUPIE); } // CHANGE PARAMETERS METHODS function transferEther(address addressToSendTo, uint256 value) { require(msg.sender == ownerAddress); addressToSendTo.transfer(value); } function changeAllowInvestment(bool _allowInvestment) { require(msg.sender == ownerAddress); allowInvestment = _allowInvestment; } function changeSaleTimes(uint256 _saleStartTime, uint256 _saleEndTime) { require(msg.sender == ownerAddress); saleStartTime = _saleStartTime; saleEndTime = _saleEndTime; } function changeEtherBonuses(uint256 _lowEtherBonusLimit, uint256 _lowEtherBonusValue, uint256 _midEtherBonusLimit, uint256 _midEtherBonusValue, uint256 _highEtherBonusLimit, uint256 _highEtherBonusValue) { require(msg.sender == ownerAddress); lowEtherBonusLimit = _lowEtherBonusLimit; lowEtherBonusValue = _lowEtherBonusValue; midEtherBonusLimit = _midEtherBonusLimit; midEtherBonusValue = _midEtherBonusValue; highEtherBonusLimit = _highEtherBonusLimit; highEtherBonusValue = _highEtherBonusValue; } function changeTimeBonuses(uint256 _highTimeBonusLimit, uint256 _highTimeBonusValue, uint256 _midTimeBonusLimit, uint256 _midTimeBonusValue, uint256 _lowTimeBonusLimit, uint256 _lowTimeBonusValue) { require(msg.sender == ownerAddress); highTimeBonusLimit = _highTimeBonusLimit; highTimeBonusValue = _highTimeBonusValue; midTimeBonusLimit = _midTimeBonusLimit; midTimeBonusValue = _midTimeBonusValue; lowTimeBonusLimit = _lowTimeBonusLimit; lowTimeBonusValue = _lowTimeBonusValue; } }
Total WEI Per Account
mapping (address => uint256) public WEIContributed;
1,779,949
[ 1, 5269, 13880, 45, 5722, 6590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 6770, 261, 2867, 516, 2254, 5034, 13, 1071, 13880, 45, 442, 11050, 31, 17322, 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, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IAuthorizer.sol"; import "./interfaces/IWETH.sol"; import "./VaultAuthorization.sol"; import "./FlashLoans.sol"; import "./Swaps.sol"; /** * @dev The `Vault` is Balancer V2's core contract. A single instance of it exists for the entire network, and it is the * entity used to interact with Pools by Liquidity Providers who join and exit them, Traders who swap, and Asset * Managers who withdraw and deposit tokens. * * The `Vault`'s source code is split among a number of sub-contracts, with the goal of improving readability and making * understanding the system easier. Most sub-contracts have been marked as `abstract` to explicitly indicate that only * the full `Vault` is meant to be deployed. * * Roughly speaking, these are the contents of each sub-contract: * * - `AssetManagers`: Pool token Asset Manager registry, and Asset Manager interactions. * - `Fees`: set and compute protocol fees. * - `FlashLoans`: flash loan transfers and fees. * - `PoolBalances`: Pool joins and exits. * - `PoolRegistry`: Pool registration, ID management, and basic queries. * - `PoolTokens`: Pool token registration and registration, and balance queries. * - `Swaps`: Pool swaps. * - `UserBalance`: manage user balances (Internal Balance operations and external balance transfers) * - `VaultAuthorization`: access control, relayers and signature validation. * * Additionally, the different Pool specializations are handled by the `GeneralPoolsBalance`, * `MinimalSwapInfoPoolsBalance` and `TwoTokenPoolsBalance` sub-contracts, which in turn make use of the * `BalanceAllocation` library. * * The most important goal of the `Vault` is to make token swaps use as little gas as possible. This is reflected in a * multitude of design decisions, from minor things like the format used to store Pool IDs, to major features such as * the different Pool specialization settings. * * Finally, the large number of tasks carried out by the Vault means its bytecode is very large, close to exceeding * the contract size limit imposed by EIP 170 (https://eips.ethereum.org/EIPS/eip-170). Manual tuning of the source code * was required to improve code generation and bring the bytecode size below this limit. This includes extensive * utilization of `internal` functions (particularly inside modifiers), usage of named return arguments, dedicated * storage access methods, dynamic revert reason generation, and usage of inline assembly, to name a few. */ contract Vault is VaultAuthorization, FlashLoans, Swaps { constructor( IAuthorizer authorizer, IWETH weth, uint256 pauseWindowDuration, uint256 bufferPeriodDuration ) VaultAuthorization(authorizer) AssetHelpers(weth) TemporarilyPausable(pauseWindowDuration, bufferPeriodDuration) { // solhint-disable-previous-line no-empty-blocks } function setPaused(bool paused) external override nonReentrant authenticate { _setPaused(paused); } // solhint-disable-next-line func-name-mixedcase function WETH() external view override returns (IWETH) { return _WETH(); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/openzeppelin/IERC20.sol"; /** * @dev Interface for the WETH token contract used internally for wrapping and unwrapping, to support * sending and receiving ETH in joins, swaps, and internal balance deposits and withdrawals. */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/helpers/TemporarilyPausable.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/SignaturesValidator.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev Manages access control of Vault permissioned functions by relying on the Authorizer and signature validation. * * Additionally handles relayer access and approval. */ abstract contract VaultAuthorization is IVault, ReentrancyGuard, Authentication, SignaturesValidator, TemporarilyPausable { // Ideally, we'd store the type hashes as immutable state variables to avoid computing the hash at runtime, but // unfortunately immutable variables cannot be used in assembly, so we just keep the precomputed hashes instead. // _JOIN_TYPE_HASH = keccak256("JoinPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _JOIN_TYPE_HASH = 0x3f7b71252bd19113ff48c19c6e004a9bcfcca320a0d74d58e85877cbd7dcae58; // _EXIT_TYPE_HASH = keccak256("ExitPool(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _EXIT_TYPE_HASH = 0x8bbc57f66ea936902f50a71ce12b92c43f3c5340bb40c27c4e90ab84eeae3353; // _SWAP_TYPE_HASH = keccak256("Swap(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _SWAP_TYPE_HASH = 0xe192dcbc143b1e244ad73b813fd3c097b832ad260a157340b4e5e5beda067abe; // _BATCH_SWAP_TYPE_HASH = keccak256("BatchSwap(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _BATCH_SWAP_TYPE_HASH = 0x9bfc43a4d98313c6766986ffd7c916c7481566d9f224c6819af0a53388aced3a; // _SET_RELAYER_TYPE_HASH = // keccak256("SetRelayerApproval(bytes calldata,address sender,uint256 nonce,uint256 deadline)"); bytes32 private constant _SET_RELAYER_TYPE_HASH = 0xa3f865aa351e51cfeb40f5178d1564bb629fe9030b83caf6361d1baaf5b90b5a; IAuthorizer private _authorizer; mapping(address => mapping(address => bool)) private _approvedRelayers; /** * @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call this function (that * is, it is a relayer for that function), and either: * a) `user` approved the caller as a relayer (via `setRelayerApproval`), or * b) a valid signature from them was appended to the calldata. * * Should only be applied to external functions. */ modifier authenticateFor(address user) { _authenticateFor(user); _; } constructor(IAuthorizer authorizer) // The Vault is a singleton, so it simply uses its own address to disambiguate action identifiers. Authentication(bytes32(uint256(address(this)))) SignaturesValidator("Balancer V2 Vault") { _setAuthorizer(authorizer); } function setAuthorizer(IAuthorizer newAuthorizer) external override nonReentrant authenticate { _setAuthorizer(newAuthorizer); } function _setAuthorizer(IAuthorizer newAuthorizer) private { emit AuthorizerChanged(newAuthorizer); _authorizer = newAuthorizer; } function getAuthorizer() external view override returns (IAuthorizer) { return _authorizer; } function setRelayerApproval( address sender, address relayer, bool approved ) external override nonReentrant whenNotPaused authenticateFor(sender) { _approvedRelayers[sender][relayer] = approved; emit RelayerApprovalChanged(relayer, sender, approved); } function hasApprovedRelayer(address user, address relayer) external view override returns (bool) { return _hasApprovedRelayer(user, relayer); } /** * @dev Reverts unless `user` is the caller, or the caller is approved by the Authorizer to call the entry point * function (that is, it is a relayer for that function) and either: * a) `user` approved the caller as a relayer (via `setRelayerApproval`), or * b) a valid signature from them was appended to the calldata. */ function _authenticateFor(address user) internal { if (msg.sender != user) { // In this context, 'permission to call a function' means 'being a relayer for a function'. _authenticateCaller(); // Being a relayer is not sufficient: `user` must have also approved the caller either via // `setRelayerApproval`, or by providing a signature appended to the calldata. if (!_hasApprovedRelayer(user, msg.sender)) { _validateSignature(user, Errors.USER_DOESNT_ALLOW_RELAYER); } } } /** * @dev Returns true if `user` approved `relayer` to act as a relayer for them. */ function _hasApprovedRelayer(address user, address relayer) internal view returns (bool) { return _approvedRelayers[user][relayer]; } function _canPerform(bytes32 actionId, address user) internal view override returns (bool) { // Access control is delegated to the Authorizer. return _authorizer.canPerform(actionId, user, address(this)); } function _typeHash() internal pure override returns (bytes32 hash) { // This is a simple switch-case statement, trivially written in Solidity by chaining else-if statements, but the // assembly implementation results in much denser bytecode. // solhint-disable-next-line no-inline-assembly assembly { // The function selector is located at the first 4 bytes of calldata. We copy the first full calldata // 256 word, and then perform a logical shift to the right, moving the selector to the least significant // 4 bytes. let selector := shr(224, calldataload(0)) // With the selector in the least significant 4 bytes, we can use 4 byte literals with leading zeros, // resulting in dense bytecode (PUSH4 opcodes). switch selector case 0xb95cac28 { hash := _JOIN_TYPE_HASH } case 0x8bdb3913 { hash := _EXIT_TYPE_HASH } case 0x52bbbe29 { hash := _SWAP_TYPE_HASH } case 0x945bcec9 { hash := _BATCH_SWAP_TYPE_HASH } case 0xfa6e671d { hash := _SET_RELAYER_TYPE_HASH } default { hash := 0x0000000000000000000000000000000000000000000000000000000000000000 } } } } // SPDX-License-Identifier: GPL-3.0-or-later // 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/>. // This flash loan provider was based on the Aave protocol's open source // implementation and terminology and interfaces are intentionally kept // similar pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./Fees.sol"; import "./interfaces/IFlashLoanRecipient.sol"; /** * @dev Handles Flash Loans through the Vault. Calls the `receiveFlashLoan` hook on the flash loan recipient * contract, which implements the `IFlashLoanRecipient` interface. */ abstract contract FlashLoans is Fees, ReentrancyGuard, TemporarilyPausable { using SafeERC20 for IERC20; function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external override nonReentrant whenNotPaused { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); uint256[] memory feeAmounts = new uint256[](tokens.length); uint256[] memory preLoanBalances = new uint256[](tokens.length); // Used to ensure `tokens` is sorted in ascending order, which ensures token uniqueness. IERC20 previousToken = IERC20(0); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; _require(token > previousToken, token == IERC20(0) ? Errors.ZERO_TOKEN : Errors.UNSORTED_TOKENS); previousToken = token; preLoanBalances[i] = token.balanceOf(address(this)); feeAmounts[i] = _calculateFlashLoanFeeAmount(amount); _require(preLoanBalances[i] >= amount, Errors.INSUFFICIENT_FLASH_LOAN_BALANCE); token.safeTransfer(address(recipient), amount); } recipient.receiveFlashLoan(tokens, amounts, feeAmounts, userData); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 preLoanBalance = preLoanBalances[i]; // Checking for loan repayment first (without accounting for fees) makes for simpler debugging, and results // in more accurate revert reasons if the flash loan protocol fee percentage is zero. uint256 postLoanBalance = token.balanceOf(address(this)); _require(postLoanBalance >= preLoanBalance, Errors.INVALID_POST_LOAN_BALANCE); // No need for checked arithmetic since we know the loan was fully repaid. uint256 receivedFeeAmount = postLoanBalance - preLoanBalance; _require(receivedFeeAmount >= feeAmounts[i], Errors.INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT); _payFeeAmount(token, receivedFeeAmount); emit FlashLoan(recipient, token, amounts[i], receivedFeeAmount); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/openzeppelin/EnumerableMap.sol"; import "../lib/openzeppelin/EnumerableSet.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeCast.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./PoolBalances.sol"; import "./interfaces/IPoolSwapStructs.sol"; import "./interfaces/IGeneralPool.sol"; import "./interfaces/IMinimalSwapInfoPool.sol"; import "./balances/BalanceAllocation.sol"; /** * Implements the Vault's high-level swap functionality. * * Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. They need not trust the Pool * contracts to do this: all security checks are made by the Vault. * * The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. * In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), * and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). * More complex swaps, such as one 'token in' to multiple tokens out can be achieved by batching together * individual swaps. */ abstract contract Swaps is ReentrancyGuard, PoolBalances { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableMap for EnumerableMap.IERC20ToBytes32Map; using Math for int256; using Math for uint256; using SafeCast for uint256; using BalanceAllocation for bytes32; function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable override nonReentrant whenNotPaused authenticateFor(funds.sender) returns (uint256 amountCalculated) { // The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy. // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.SWAP_DEADLINE); // This revert reason is for consistency with `batchSwap`: an equivalent `swap` performed using that function // would result in this error. _require(singleSwap.amount > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP); IERC20 tokenIn = _translateToIERC20(singleSwap.assetIn); IERC20 tokenOut = _translateToIERC20(singleSwap.assetOut); _require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN); // Initializing each struct field one-by-one uses less gas than setting all at once. IPoolSwapStructs.SwapRequest memory poolRequest; poolRequest.poolId = singleSwap.poolId; poolRequest.kind = singleSwap.kind; poolRequest.tokenIn = tokenIn; poolRequest.tokenOut = tokenOut; poolRequest.amount = singleSwap.amount; poolRequest.userData = singleSwap.userData; poolRequest.from = funds.sender; poolRequest.to = funds.recipient; // The lastChangeBlock field is left uninitialized. uint256 amountIn; uint256 amountOut; (amountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest); _require(singleSwap.kind == SwapKind.GIVEN_IN ? amountOut >= limit : amountIn <= limit, Errors.SWAP_LIMIT); _receiveAsset(singleSwap.assetIn, amountIn, funds.sender, funds.fromInternalBalance); _sendAsset(singleSwap.assetOut, amountOut, funds.recipient, funds.toInternalBalance); // If the asset in is ETH, then `amountIn` ETH was wrapped into WETH. _handleRemainingEth(_isETH(singleSwap.assetIn) ? amountIn : 0); } function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable override nonReentrant whenNotPaused authenticateFor(funds.sender) returns (int256[] memory assetDeltas) { // The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy. // solhint-disable-next-line not-rely-on-time _require(block.timestamp <= deadline, Errors.SWAP_DEADLINE); InputHelpers.ensureInputLengthMatch(assets.length, limits.length); // Perform the swaps, updating the Pool token balances and computing the net Vault asset deltas. assetDeltas = _swapWithPools(swaps, assets, funds, kind); // Process asset deltas, by either transferring assets from the sender (for positive deltas) or to the recipient // (for negative deltas). uint256 wrappedEth = 0; for (uint256 i = 0; i < assets.length; ++i) { IAsset asset = assets[i]; int256 delta = assetDeltas[i]; _require(delta <= limits[i], Errors.SWAP_LIMIT); if (delta > 0) { uint256 toReceive = uint256(delta); _receiveAsset(asset, toReceive, funds.sender, funds.fromInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(toReceive); } } else if (delta < 0) { uint256 toSend = uint256(-delta); _sendAsset(asset, toSend, funds.recipient, funds.toInternalBalance); } } // Handle any used and remaining ETH. _handleRemainingEth(wrappedEth); } // For `_swapWithPools` to handle both 'given in' and 'given out' swaps, it internally tracks the 'given' amount // (supplied by the caller), and the 'calculated' amount (returned by the Pool in response to the swap request). /** * @dev Given the two swap tokens and the swap kind, returns which one is the 'given' token (the token whose * amount is supplied by the caller). */ function _tokenGiven( SwapKind kind, IERC20 tokenIn, IERC20 tokenOut ) private pure returns (IERC20) { return kind == SwapKind.GIVEN_IN ? tokenIn : tokenOut; } /** * @dev Given the two swap tokens and the swap kind, returns which one is the 'calculated' token (the token whose * amount is calculated by the Pool). */ function _tokenCalculated( SwapKind kind, IERC20 tokenIn, IERC20 tokenOut ) private pure returns (IERC20) { return kind == SwapKind.GIVEN_IN ? tokenOut : tokenIn; } /** * @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind. */ function _getAmounts( SwapKind kind, uint256 amountGiven, uint256 amountCalculated ) private pure returns (uint256 amountIn, uint256 amountOut) { if (kind == SwapKind.GIVEN_IN) { (amountIn, amountOut) = (amountGiven, amountCalculated); } else { // SwapKind.GIVEN_OUT (amountIn, amountOut) = (amountCalculated, amountGiven); } } /** * @dev Performs all `swaps`, calling swap hooks on the Pool contracts and updating their balances. Does not cause * any transfer of tokens - instead it returns the net Vault token deltas: positive if the Vault should receive * tokens, and negative if it should send them. */ function _swapWithPools( BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, SwapKind kind ) private returns (int256[] memory assetDeltas) { assetDeltas = new int256[](assets.length); // These variables could be declared inside the loop, but that causes the compiler to allocate memory on each // loop iteration, increasing gas costs. BatchSwapStep memory batchSwapStep; IPoolSwapStructs.SwapRequest memory poolRequest; // These store data about the previous swap here to implement multihop logic across swaps. IERC20 previousTokenCalculated; uint256 previousAmountCalculated; for (uint256 i = 0; i < swaps.length; ++i) { batchSwapStep = swaps[i]; bool withinBounds = batchSwapStep.assetInIndex < assets.length && batchSwapStep.assetOutIndex < assets.length; _require(withinBounds, Errors.OUT_OF_BOUNDS); IERC20 tokenIn = _translateToIERC20(assets[batchSwapStep.assetInIndex]); IERC20 tokenOut = _translateToIERC20(assets[batchSwapStep.assetOutIndex]); _require(tokenIn != tokenOut, Errors.CANNOT_SWAP_SAME_TOKEN); // Sentinel value for multihop logic if (batchSwapStep.amount == 0) { // When the amount given is zero, we use the calculated amount for the previous swap, as long as the // current swap's given token is the previous calculated token. This makes it possible to swap a // given amount of token A for token B, and then use the resulting token B amount to swap for token C. _require(i > 0, Errors.UNKNOWN_AMOUNT_IN_FIRST_SWAP); bool usingPreviousToken = previousTokenCalculated == _tokenGiven(kind, tokenIn, tokenOut); _require(usingPreviousToken, Errors.MALCONSTRUCTED_MULTIHOP_SWAP); batchSwapStep.amount = previousAmountCalculated; } // Initializing each struct field one-by-one uses less gas than setting all at once poolRequest.poolId = batchSwapStep.poolId; poolRequest.kind = kind; poolRequest.tokenIn = tokenIn; poolRequest.tokenOut = tokenOut; poolRequest.amount = batchSwapStep.amount; poolRequest.userData = batchSwapStep.userData; poolRequest.from = funds.sender; poolRequest.to = funds.recipient; // The lastChangeBlock field is left uninitialized uint256 amountIn; uint256 amountOut; (previousAmountCalculated, amountIn, amountOut) = _swapWithPool(poolRequest); previousTokenCalculated = _tokenCalculated(kind, tokenIn, tokenOut); // Accumulate Vault deltas across swaps assetDeltas[batchSwapStep.assetInIndex] = assetDeltas[batchSwapStep.assetInIndex].add(amountIn.toInt256()); assetDeltas[batchSwapStep.assetOutIndex] = assetDeltas[batchSwapStep.assetOutIndex].sub( amountOut.toInt256() ); } } /** * @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and * updating the Pool's balance. * * Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind. */ function _swapWithPool(IPoolSwapStructs.SwapRequest memory request) private returns ( uint256 amountCalculated, uint256 amountIn, uint256 amountOut ) { // Get the calculated amount from the Pool and update its balances address pool = _getPoolAddress(request.poolId); PoolSpecialization specialization = _getPoolSpecialization(request.poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { amountCalculated = _processTwoTokenPoolSwapRequest(request, IMinimalSwapInfoPool(pool)); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { amountCalculated = _processMinimalSwapInfoPoolSwapRequest(request, IMinimalSwapInfoPool(pool)); } else { // PoolSpecialization.GENERAL amountCalculated = _processGeneralPoolSwapRequest(request, IGeneralPool(pool)); } (amountIn, amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); emit Swap(request.poolId, request.tokenIn, request.tokenOut, amountIn, amountOut); } function _processTwoTokenPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool) private returns (uint256 amountCalculated) { // For gas efficiency reasons, this function uses low-level knowledge of how Two Token Pool balances are // stored internally, instead of using getters and setters for all operations. ( bytes32 tokenABalance, bytes32 tokenBBalance, TwoTokenPoolBalances storage poolBalances ) = _getTwoTokenPoolSharedBalances(request.poolId, request.tokenIn, request.tokenOut); // We have the two Pool balances, but we don't know which one is 'token in' or 'token out'. bytes32 tokenInBalance; bytes32 tokenOutBalance; // In Two Token Pools, token A has a smaller address than token B if (request.tokenIn < request.tokenOut) { // in is A, out is B tokenInBalance = tokenABalance; tokenOutBalance = tokenBBalance; } else { // in is B, out is A tokenOutBalance = tokenABalance; tokenInBalance = tokenBBalance; } // Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap (tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook( request, pool, tokenInBalance, tokenOutBalance ); // We check the token ordering again to create the new shared cash packed struct poolBalances.sharedCash = request.tokenIn < request.tokenOut ? BalanceAllocation.toSharedCash(tokenInBalance, tokenOutBalance) // in is A, out is B : BalanceAllocation.toSharedCash(tokenOutBalance, tokenInBalance); // in is B, out is A } function _processMinimalSwapInfoPoolSwapRequest( IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool ) private returns (uint256 amountCalculated) { bytes32 tokenInBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenIn); bytes32 tokenOutBalance = _getMinimalSwapInfoPoolBalance(request.poolId, request.tokenOut); // Perform the swap request and compute the new balances for 'token in' and 'token out' after the swap (tokenInBalance, tokenOutBalance, amountCalculated) = _callMinimalSwapInfoPoolOnSwapHook( request, pool, tokenInBalance, tokenOutBalance ); _minimalSwapInfoPoolsBalances[request.poolId][request.tokenIn] = tokenInBalance; _minimalSwapInfoPoolsBalances[request.poolId][request.tokenOut] = tokenOutBalance; } /** * @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token * Pools do this. */ function _callMinimalSwapInfoPoolOnSwapHook( IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool, bytes32 tokenInBalance, bytes32 tokenOutBalance ) internal returns ( bytes32 newTokenInBalance, bytes32 newTokenOutBalance, uint256 amountCalculated ) { uint256 tokenInTotal = tokenInBalance.total(); uint256 tokenOutTotal = tokenOutBalance.total(); request.lastChangeBlock = Math.max(tokenInBalance.lastChangeBlock(), tokenOutBalance.lastChangeBlock()); // Perform the swap request callback, and compute the new balances for 'token in' and 'token out' after the swap amountCalculated = pool.onSwap(request, tokenInTotal, tokenOutTotal); (uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); newTokenInBalance = tokenInBalance.increaseCash(amountIn); newTokenOutBalance = tokenOutBalance.decreaseCash(amountOut); } function _processGeneralPoolSwapRequest(IPoolSwapStructs.SwapRequest memory request, IGeneralPool pool) private returns (uint256 amountCalculated) { bytes32 tokenInBalance; bytes32 tokenOutBalance; // We access both token indexes without checking existence, because we will do it manually immediately after. EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId]; uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn); uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut); if (indexIn == 0 || indexOut == 0) { // The tokens might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(request.poolId); _revert(Errors.TOKEN_NOT_REGISTERED); } // EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid, // we can undo this. indexIn -= 1; indexOut -= 1; uint256 tokenAmount = poolBalances.length(); uint256[] memory currentBalances = new uint256[](tokenAmount); request.lastChangeBlock = 0; for (uint256 i = 0; i < tokenAmount; i++) { // Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we // know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads. bytes32 balance = poolBalances.unchecked_valueAt(i); currentBalances[i] = balance.total(); request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock()); if (i == indexIn) { tokenInBalance = balance; } else if (i == indexOut) { tokenOutBalance = balance; } } // Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut); (uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); tokenInBalance = tokenInBalance.increaseCash(amountIn); tokenOutBalance = tokenOutBalance.decreaseCash(amountOut); // Because no tokens were registered or deregistered between now or when we retrieved the indexes for // 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads. poolBalances.unchecked_setAt(indexIn, tokenInBalance); poolBalances.unchecked_setAt(indexOut, tokenOutBalance); } // This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external override returns (int256[] memory) { // In order to accurately 'simulate' swaps, this function actually does perform the swaps, including calling the // Pool hooks and updating balances in storage. However, once it computes the final Vault Deltas, it // reverts unconditionally, returning this array as the revert data. // // By wrapping this reverting call, we can decode the deltas 'returned' and return them as a normal Solidity // function would. The only caveat is the function becomes non-view, but off-chain clients can still call it // via eth_call to get the expected result. // // This technique was inspired by the work from the Gnosis team in the Gnosis Safe contract: // https://github.com/gnosis/safe-contracts/blob/v1.2.0/contracts/GnosisSafe.sol#L265 // // Most of this function is implemented using inline assembly, as the actual work it needs to do is not // significant, and Solidity is not particularly well-suited to generate this behavior, resulting in a large // amount of generated bytecode. if (msg.sender != address(this)) { // We perform an external call to ourselves, forwarding the same calldata. In this call, the else clause of // the preceding if statement will be executed instead. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(msg.data); // solhint-disable-next-line no-inline-assembly assembly { // This call should always revert to decode the actual asset deltas from the revert reason switch success case 0 { // Note we are manually writing the memory slot 0. We can safely overwrite whatever is // stored there as we take full control of the execution and then immediately return. // We copy the first 4 bytes to check if it matches with the expected signature, otherwise // there was another revert reason and we should forward it. returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000) // If the first 4 bytes don't match with the expected signature, we forward the revert reason. if eq(eq(error, 0xfa61cc1200000000000000000000000000000000000000000000000000000000), 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } // The returndata contains the signature, followed by the raw memory representation of an array: // length + data. We need to return an ABI-encoded representation of this array. // An ABI-encoded array contains an additional field when compared to its raw memory // representation: an offset to the location of the length. The offset itself is 32 bytes long, // so the smallest value we can use is 32 for the data to be located immediately after it. mstore(0, 32) // We now copy the raw memory array from returndata into memory. Since the offset takes up 32 // bytes, we start copying at address 0x20. We also get rid of the error signature, which takes // the first four bytes of returndata. let size := sub(returndatasize(), 0x04) returndatacopy(0x20, 0x04, size) // We finally return the ABI-encoded array, which has a total length equal to that of the array // (returndata), plus the 32 bytes for the offset. return(0, add(size, 32)) } default { // This call should always revert, but we fail nonetheless if that didn't happen invalid() } } } else { int256[] memory deltas = _swapWithPools(swaps, assets, funds, kind); // solhint-disable-next-line no-inline-assembly assembly { // We will return a raw representation of the array in memory, which is composed of a 32 byte length, // followed by the 32 byte int256 values. Because revert expects a size in bytes, we multiply the array // length (stored at `deltas`) by 32. let size := mul(mload(deltas), 32) // We send one extra value for the error signature "QueryError(int256[])" which is 0xfa61cc12. // We store it in the previous slot to the `deltas` array. We know there will be at least one available // slot due to how the memory scratch space works. // We can safely overwrite whatever is stored in this slot as we will revert immediately after that. mstore(sub(deltas, 0x20), 0x00000000000000000000000000000000000000000000000000000000fa61cc12) let start := sub(deltas, 0x04) // When copying from `deltas` into returndata, we copy an additional 36 bytes to also return the array's // length and the error signature. revert(start, add(size, 36)) } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ITemporarilyPausable.sol"; /** * @dev Allows for a contract to be paused during an initial period after deployment, disabling functionality. Can be * used as an emergency switch in case a security vulnerability or threat is identified. * * The contract can only be paused during the Pause Window, a period that starts at deployment. It can also be * unpaused and repaused any number of times during this period. This is intended to serve as a safety measure: it lets * system managers react quickly to potentially dangerous situations, knowing that this action is reversible if careful * analysis later determines there was a false alarm. * * If the contract is paused when the Pause Window finishes, it will remain in the paused state through an additional * Buffer Period, after which it will be automatically unpaused forever. This is to ensure there is always enough time * to react to an emergency, even if the threat is discovered shortly before the Pause Window expires. * * Note that since the contract can only be paused within the Pause Window, unpausing during the Buffer Period is * irreversible. */ abstract contract TemporarilyPausable is ITemporarilyPausable { // The Pause Window and Buffer Period are timestamp-based: they should not be relied upon for sub-minute accuracy. // solhint-disable not-rely-on-time uint256 private constant _MAX_PAUSE_WINDOW_DURATION = 90 days; uint256 private constant _MAX_BUFFER_PERIOD_DURATION = 30 days; uint256 private immutable _pauseWindowEndTime; uint256 private immutable _bufferPeriodEndTime; bool private _paused; constructor(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) { _require(pauseWindowDuration <= _MAX_PAUSE_WINDOW_DURATION, Errors.MAX_PAUSE_WINDOW_DURATION); _require(bufferPeriodDuration <= _MAX_BUFFER_PERIOD_DURATION, Errors.MAX_BUFFER_PERIOD_DURATION); uint256 pauseWindowEndTime = block.timestamp + pauseWindowDuration; _pauseWindowEndTime = pauseWindowEndTime; _bufferPeriodEndTime = pauseWindowEndTime + bufferPeriodDuration; } /** * @dev Reverts if the contract is paused. */ modifier whenNotPaused() { _ensureNotPaused(); _; } /** * @dev Returns the current contract pause status, as well as the end times of the Pause Window and Buffer * Period. */ function getPausedState() external view override returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ) { paused = !_isNotPaused(); pauseWindowEndTime = _getPauseWindowEndTime(); bufferPeriodEndTime = _getBufferPeriodEndTime(); } /** * @dev Sets the pause state to `paused`. The contract can only be paused until the end of the Pause Window, and * unpaused until the end of the Buffer Period. * * Once the Buffer Period expires, this function reverts unconditionally. */ function _setPaused(bool paused) internal { if (paused) { _require(block.timestamp < _getPauseWindowEndTime(), Errors.PAUSE_WINDOW_EXPIRED); } else { _require(block.timestamp < _getBufferPeriodEndTime(), Errors.BUFFER_PERIOD_EXPIRED); } _paused = paused; emit PausedStateChanged(paused); } /** * @dev Reverts if the contract is paused. */ function _ensureNotPaused() internal view { _require(_isNotPaused(), Errors.PAUSED); } /** * @dev Returns true if the contract is unpaused. * * Once the Buffer Period expires, the gas cost of calling this function is reduced dramatically, as storage is no * longer accessed. */ function _isNotPaused() internal view returns (bool) { // After the Buffer Period, the (inexpensive) timestamp check short-circuits the storage access. return block.timestamp > _getBufferPeriodEndTime() || !_paused; } // These getters lead to reduced bytecode size by inlining the immutable variables in a single place. function _getPauseWindowEndTime() private view returns (uint256) { return _pauseWindowEndTime; } function _getBufferPeriodEndTime() private view returns (uint256) { return _bufferPeriodEndTime; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./ISignaturesValidator.sol"; import "../openzeppelin/EIP712.sol"; /** * @dev Utility for signing Solidity function calls. * * This contract relies on the fact that Solidity contracts can be called with extra calldata, and enables * meta-transaction schemes by appending an EIP712 signature of the original calldata at the end. * * Derived contracts must implement the `_typeHash` function to map function selectors to EIP712 structs. */ abstract contract SignaturesValidator is ISignaturesValidator, EIP712 { // The appended data consists of a deadline, plus the [v,r,s] signature. For simplicity, we use a full 256 bit slot // for each of these values, even if 'v' is typically an 8 bit value. uint256 internal constant _EXTRA_CALLDATA_LENGTH = 4 * 32; // Replay attack prevention for each user. mapping(address => uint256) internal _nextNonce; constructor(string memory name) EIP712(name, "1") { // solhint-disable-previous-line no-empty-blocks } function getDomainSeparator() external view override returns (bytes32) { return _domainSeparatorV4(); } function getNextNonce(address user) external view override returns (uint256) { return _nextNonce[user]; } /** * @dev Reverts with `errorCode` unless a valid signature for `user` was appended to the calldata. */ function _validateSignature(address user, uint256 errorCode) internal { uint256 nextNonce = _nextNonce[user]++; _require(_isSignatureValid(user, nextNonce), errorCode); } function _isSignatureValid(address user, uint256 nonce) private view returns (bool) { uint256 deadline = _deadline(); // The deadline is timestamp-based: it should not be relied upon for sub-minute accuracy. // solhint-disable-next-line not-rely-on-time if (deadline < block.timestamp) { return false; } bytes32 typeHash = _typeHash(); if (typeHash == bytes32(0)) { // Prevent accidental signature validation for functions that don't have an associated type hash. return false; } // All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline). bytes32 structHash = keccak256(abi.encode(typeHash, keccak256(_calldata()), msg.sender, nonce, deadline)); bytes32 digest = _hashTypedDataV4(structHash); (uint8 v, bytes32 r, bytes32 s) = _signature(); address recoveredAddress = ecrecover(digest, v, r, s); // ecrecover returns the zero address on recover failure, so we need to handle that explicitly. return recoveredAddress != address(0) && recoveredAddress == user; } /** * @dev Returns the EIP712 type hash for the current entry point function, which can be identified by its function * selector (available as `msg.sig`). * * The type hash must conform to the following format: * <name>(bytes calldata, address sender, uint256 nonce, uint256 deadline) * * If 0x00, all signatures will be considered invalid. */ function _typeHash() internal view virtual returns (bytes32); /** * @dev Extracts the signature deadline from extra calldata. * * This function returns bogus data if no signature is included. */ function _deadline() internal pure returns (uint256) { // The deadline is the first extra argument at the end of the original calldata. return uint256(_decodeExtraCalldataWord(0)); } /** * @dev Extracts the signature parameters from extra calldata. * * This function returns bogus data if no signature is included. This is not a security risk, as that data would not * be considered a valid signature in the first place. */ function _signature() internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // v, r and s are appended after the signature deadline, in that order. v = uint8(uint256(_decodeExtraCalldataWord(0x20))); r = _decodeExtraCalldataWord(0x40); s = _decodeExtraCalldataWord(0x60); } /** * @dev Returns the original calldata, without the extra bytes containing the signature. * * This function returns bogus data if no signature is included. */ function _calldata() internal pure returns (bytes memory result) { result = msg.data; // A calldata to memory assignment results in memory allocation and copy of contents. if (result.length > _EXTRA_CALLDATA_LENGTH) { // solhint-disable-next-line no-inline-assembly assembly { // We simply overwrite the array length with the reduced one. mstore(result, sub(calldatasize(), _EXTRA_CALLDATA_LENGTH)) } } } /** * @dev Returns a 256 bit word from 'extra' calldata, at some offset from the expected end of the original calldata. * * This function returns bogus data if no signature is included. */ function _decodeExtraCalldataWord(uint256 offset) private pure returns (bytes32 result) { // solhint-disable-next-line no-inline-assembly assembly { result := calldataload(add(sub(calldatasize(), _EXTRA_CALLDATA_LENGTH), offset)) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; // Based on the ReentrancyGuard library from OpenZeppelin contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs but reduced bytecode size. /** * @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() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "../ProtocolFeesCollector.sol"; import "../../lib/helpers/ISignaturesValidator.sol"; import "../../lib/helpers/ITemporarilyPausable.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (ProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _HASHED_NAME = keccak256(bytes(name)); _HASHED_VERSION = keccak256(bytes(version)); _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { // Silence state mutability warning without generating bytecode. // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and // https://github.com/ethereum/solidity/issues/2691 this; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "../../lib/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/helpers/Authentication.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IAuthorizer.sol"; /** * @dev This an auxiliary contract to the Vault, deployed by it during construction. It offloads some of the tasks the * Vault performs to reduce its overall bytecode size. * * The current values for all protocol fee percentages are stored here, and any tokens charged as protocol fees are * sent to this contract, where they may be withdrawn by authorized entities. All authorization tasks are delegated * to the Vault's own authorizer. */ contract ProtocolFeesCollector is Authentication, ReentrancyGuard { using SafeERC20 for IERC20; // Absolute maximum fee percentages (1e18 = 100%, 1e16 = 1%). uint256 private constant _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE = 50e16; // 50% uint256 private constant _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE = 1e16; // 1% IVault public immutable vault; // All fee percentages are 18-decimal fixed point numbers. // The swap fee is charged whenever a swap occurs, as a percentage of the fee charged by the Pool. These are not // actually charged on each individual swap: the `Vault` relies on the Pools being honest and reporting fees due // when users join and exit them. uint256 private _swapFeePercentage; // The flash loan fee is charged whenever a flash loan occurs, as a percentage of the tokens lent. uint256 private _flashLoanFeePercentage; event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); constructor(IVault _vault) // The ProtocolFeesCollector is a singleton, so it simply uses its own address to disambiguate action // identifiers. Authentication(bytes32(uint256(address(this)))) { vault = _vault; } function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external nonReentrant authenticate { InputHelpers.ensureInputLengthMatch(tokens.length, amounts.length); for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; uint256 amount = amounts[i]; token.safeTransfer(recipient, amount); } } function setSwapFeePercentage(uint256 newSwapFeePercentage) external authenticate { _require(newSwapFeePercentage <= _MAX_PROTOCOL_SWAP_FEE_PERCENTAGE, Errors.SWAP_FEE_PERCENTAGE_TOO_HIGH); _swapFeePercentage = newSwapFeePercentage; emit SwapFeePercentageChanged(newSwapFeePercentage); } function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external authenticate { _require( newFlashLoanFeePercentage <= _MAX_PROTOCOL_FLASH_LOAN_FEE_PERCENTAGE, Errors.FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH ); _flashLoanFeePercentage = newFlashLoanFeePercentage; emit FlashLoanFeePercentageChanged(newFlashLoanFeePercentage); } function getSwapFeePercentage() external view returns (uint256) { return _swapFeePercentage; } function getFlashLoanFeePercentage() external view returns (uint256) { return _flashLoanFeePercentage; } function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts) { feeAmounts = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { feeAmounts[i] = tokens[i].balanceOf(address(this)); } } function getAuthorizer() external view returns (IAuthorizer) { return _getAuthorizer(); } function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return _getAuthorizer().canPerform(actionId, account, address(this)); } function _getAuthorizer() internal view returns (IAuthorizer) { return vault.getAuthorizer(); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "./BalancerErrors.sol"; import "../../vault/interfaces/IAsset.sol"; library InputHelpers { function ensureInputLengthMatch(uint256 a, uint256 b) internal pure { _require(a == b, Errors.INPUT_LENGTH_MISMATCH); } function ensureInputLengthMatch( uint256 a, uint256 b, uint256 c ) internal pure { _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH); } function ensureArrayIsSorted(IAsset[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(IERC20[] memory array) internal pure { address[] memory addressArray; // solhint-disable-next-line no-inline-assembly assembly { addressArray := array } ensureArrayIsSorted(addressArray); } function ensureArrayIsSorted(address[] memory array) internal pure { if (array.length < 2) { return; } address previous = array[0]; for (uint256 i = 1; i < array.length; ++i) { address current = array[i]; _require(previous < current, Errors.UNSORTED_ARRAY); previous = current; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; import "./IERC20.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 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @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). * * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert. */ function _callOptionalReturn(address 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. (bool success, bytes memory returndata) = token.call(data); // If the low-level call didn't succeed we return whatever was returned from it. assembly { if eq(success, 0) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/FixedPoint.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./ProtocolFeesCollector.sol"; import "./VaultAuthorization.sol"; import "./interfaces/IVault.sol"; /** * @dev To reduce the bytecode size of the Vault, most of the protocol fee logic is not here, but in the * ProtocolFeesCollector contract. */ abstract contract Fees is IVault { using SafeERC20 for IERC20; ProtocolFeesCollector private immutable _protocolFeesCollector; constructor() { _protocolFeesCollector = new ProtocolFeesCollector(IVault(this)); } function getProtocolFeesCollector() public view override returns (ProtocolFeesCollector) { return _protocolFeesCollector; } /** * @dev Returns the protocol swap fee percentage. */ function _getProtocolSwapFeePercentage() internal view returns (uint256) { return getProtocolFeesCollector().getSwapFeePercentage(); } /** * @dev Returns the protocol fee amount to charge for a flash loan of `amount`. */ function _calculateFlashLoanFeeAmount(uint256 amount) internal view returns (uint256) { // Fixed point multiplication introduces error: we round up, which means in certain scenarios the charged // percentage can be slightly higher than intended. uint256 percentage = getProtocolFeesCollector().getFlashLoanFeePercentage(); return FixedPoint.mulUp(amount, percentage); } function _payFeeAmount(IERC20 token, uint256 amount) internal { if (amount > 0) { token.safeTransfer(address(getProtocolFeesCollector()), amount); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./LogExpMath.sol"; import "../helpers/BalancerErrors.sol"; /* solhint-disable private-vars-leading-underscore */ library FixedPoint { uint256 internal constant ONE = 1e18; // 18 decimal places uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14) // Minimum base for the power function when the exponent is 'free' (larger than ONE). uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18; function add(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { // Fixed Point addition is the same as regular checked addition _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); return product / ONE; } function mulUp(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW); if (product == 0) { return 0; } else { // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((product - 1) / ONE) + 1; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow return aInflated / b; } } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { uint256 aInflated = a * ONE; _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow // The traditional divUp formula is: // divUp(x, y) := (x + y - 1) / y // To avoid intermediate overflow in the addition, we distribute the division and get: // divUp(x, y) := (x - 1) / y + 1 // Note that this requires x != 0, which we already tested for. return ((aInflated - 1) / b) + 1; } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above * the true value (that is, the error function expected - actual is always positive). */ function powDown(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); if (raw < maxError) { return 0; } else { return sub(raw, maxError); } } /** * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below * the true value (that is, the error function expected - actual is always negative). */ function powUp(uint256 x, uint256 y) internal pure returns (uint256) { uint256 raw = LogExpMath.pow(x, y); uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1); return add(raw, maxError); } /** * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1. * * Useful when computing the complement for values with some level of relative error, as it strips this error and * prevents intermediate negative values. */ function complement(uint256 x) internal pure returns (uint256) { return (x < ONE) ? (ONE - x) : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later // 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 internal License for more details. // You should have received a copy of the GNU General internal License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. _require(x < 2**255, Errors.X_OUT_OF_BOUNDS); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y _require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, Errors.PRODUCT_OUT_OF_BOUNDS ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. _require(a > 0, Errors.OUT_OF_BOUNDS); if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = ln_36(base); } else { logBase = ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = ln_36(arg); } else { logArg = ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev High precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library */ library Math { /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting 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), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting 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), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // Based on the EnumerableMap library from OpenZeppelin contracts, altered to include the following: // * a map from IERC20 to bytes32 // * entries are stored in mappings instead of arrays, reducing implicit storage reads for out-of-bounds checks // * unchecked_at and unchecked_valueAt, which allow for more gas efficient data reads in some scenarios // * unchecked_indexOf and unchecked_setAt, which allow for more gas efficient data writes in some scenarios // // Additionally, the base private functions that work on bytes32 were removed and replaced with a native implementation // for IERC20 keys, to reduce bytecode size and runtime costs. // We're using non-standard casing for the unchecked functions to differentiate them, so we need to turn off that rule // solhint-disable func-name-mixedcase import "./IERC20.sol"; import "../helpers/BalancerErrors.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` */ library EnumerableMap { // The original OpenZeppelin implementation uses a generic Map type with bytes32 keys: this was replaced with // IERC20ToBytes32Map, which uses IERC20 keys natively, resulting in more dense bytecode. struct IERC20ToBytes32MapEntry { IERC20 _key; bytes32 _value; } struct IERC20ToBytes32Map { // Number of entries in the map uint256 _length; // Storage of map keys and values mapping(uint256 => IERC20ToBytes32MapEntry) _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(IERC20 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( IERC20ToBytes32Map storage map, IERC20 key, bytes32 value ) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to !contains(map, key) if (keyIndex == 0) { uint256 previousLength = map._length; map._entries[previousLength] = IERC20ToBytes32MapEntry({ _key: key, _value: value }); map._length = previousLength + 1; // The entry is stored at previousLength, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = previousLength + 1; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Updates the value for an entry, given its key's index. The key index can be retrieved via * {unchecked_indexOf}, and it should be noted that key indices may change when calling {set} or {remove}. O(1). * * This function performs one less storage read than {set}, but it should only be used when `index` is known to be * within bounds. */ function unchecked_setAt( IERC20ToBytes32Map storage map, uint256 index, bytes32 value ) internal { map._entries[index]._value = value; } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(IERC20ToBytes32Map storage map, IERC20 key) internal returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; // Equivalent to contains(map, key) if (keyIndex != 0) { // To delete a key-value pair from the _entries pseudo-array in O(1), we swap the entry to delete with the // one at the highest index, and then remove this last entry (sometimes called as 'swap and pop'). // This modifies the order of the pseudo-array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. IERC20ToBytes32MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored delete map._entries[lastIndex]; map._length = lastIndex; // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function contains(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function length(IERC20ToBytes32Map storage map) internal view returns (uint256) { return map._length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { _require(map._length > index, Errors.OUT_OF_BOUNDS); return unchecked_at(map, index); } /** * @dev Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or larger * than {length}). O(1). * * This function performs one less storage read than {at}, but should only be used when `index` is known to be * within bounds. */ function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { IERC20ToBytes32MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Same as {unchecked_At}, except it only returns the value and not the key (performing one less storage * read). O(1). */ function unchecked_valueAt(IERC20ToBytes32Map storage map, uint256 index) internal view returns (bytes32) { return map._entries[index]._value; } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. Reverts with `errorCode` otherwise. */ function get( IERC20ToBytes32Map storage map, IERC20 key, uint256 errorCode ) internal view returns (bytes32) { uint256 index = map._indexes[key]; _require(index > 0, errorCode); return unchecked_valueAt(map, index - 1); } /** * @dev Returns the index for `key` **plus one**. Does not revert if the key is not in the map, and returns 0 * instead. */ function unchecked_indexOf(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (uint256) { return map._indexes[key]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; // Based on the EnumerableSet library from OpenZeppelin contracts, altered to remove the base private functions that // work on bytes32, replacing them with a native implementation for address values, to reduce bytecode size and runtime // costs. // The `unchecked_at` function was also added, which allows for more gas efficient data reads in some scenarios. /** * @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 { // The original OpenZeppelin implementation uses a generic Set type with bytes32 values: this was replaced with // AddressSet, which uses address keys natively, resulting in more dense bytecode. struct AddressSet { // Storage of set values address[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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. address 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(AddressSet storage set, address value) internal view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) { _require(set._values.length > index, Errors.OUT_OF_BOUNDS); return unchecked_at(set, index); } /** * @dev Same as {at}, except this doesn't revert if `index` it outside of the set (i.e. if it is equal or larger * than {length}). O(1). * * This function performs one less storage read than {at}, but should only be used when `index` is known to be * within bounds. */ function unchecked_at(AddressSet storage set, uint256 index) internal view returns (address) { return set._values[index]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev 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, Errors.SAFE_CAST_VALUE_CANT_FIT_INT256); return int256(value); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./Fees.sol"; import "./PoolTokens.sol"; import "./UserBalance.sol"; import "./interfaces/IBasePool.sol"; /** * @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces, * such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool` * and `getPoolTokens`, delegating to specialization-specific functions as needed. * * `managePoolBalance` handles all Asset Manager interactions. */ abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance { using Math for uint256; using SafeERC20 for IERC20; using BalanceAllocation for bytes32; using BalanceAllocation for bytes32[]; function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable override whenNotPaused { // This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead. // Note that `recipient` is not actually payable in the context of a join - we cast it because we handle both // joins and exits at once. _joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request)); } function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external override { // This function doesn't have the nonReentrant modifier: it is applied to `_joinOrExit` instead. _joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request)); } // This has the exact same layout as JoinPoolRequest and ExitPoolRequest, except the `maxAmountsIn` and // `minAmountsOut` are called `limits`. Internally we use this struct for both since these two functions are quite // similar, but expose the others to callers for clarity. struct PoolBalanceChange { IAsset[] assets; uint256[] limits; bytes userData; bool useInternalBalance; } /** * @dev Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost. */ function _toPoolBalanceChange(JoinPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { // solhint-disable-next-line no-inline-assembly assembly { change := request } } /** * @dev Converts an ExitPoolRequest into a PoolBalanceChange, with no runtime cost. */ function _toPoolBalanceChange(ExitPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { // solhint-disable-next-line no-inline-assembly assembly { change := request } } /** * @dev Implements both `joinPool` and `exitPool`, based on `kind`. */ function _joinOrExit( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change ) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) { // This function uses a large number of stack variables (poolId, sender and recipient, balances, amounts, fees, // etc.), which leads to 'stack too deep' issues. It relies on private functions with seemingly arbitrary // interfaces to work around this limitation. InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length); // We first check that the caller passed the Pool's registered tokens in the correct order, and retrieve the // current balance for each. IERC20[] memory tokens = _translateToIERC20(change.assets); bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens); // The bulk of the work is done here: the corresponding Pool hook is called, its final balances are computed, // assets are transferred, and fees are paid. ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory paidProtocolSwapFeeAmounts ) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances); // All that remains is storing the new Pool balances. PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances); } else { // PoolSpecialization.GENERAL _setGeneralPoolBalances(poolId, finalBalances); } bool positive = kind == PoolBalanceChangeKind.JOIN; // Amounts in are positive, out are negative emit PoolBalanceChanged( poolId, sender, tokens, // We can unsafely cast to int256 because balances are actually stored as uint112 _unsafeCastToInt256(amountsInOrOut, positive), paidProtocolSwapFeeAmounts ); } /** * @dev Calls the corresponding Pool hook to get the amounts in/out plus protocol fee amounts, and performs the * associated token transfers and fee payments, returning the Pool's final balances. */ function _callPoolBalanceChange( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances ) private returns ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory dueProtocolFeeAmounts ) { (uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock(); IBasePool pool = IBasePool(_getPoolAddress(poolId)); (amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN ? pool.onJoinPool( poolId, sender, recipient, totalBalances, lastChangeBlock, _getProtocolSwapFeePercentage(), change.userData ) : pool.onExitPool( poolId, sender, recipient, totalBalances, lastChangeBlock, _getProtocolSwapFeePercentage(), change.userData ); InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length); // The Vault ignores the `recipient` in joins and the `sender` in exits: it is up to the Pool to keep track of // their participation. finalBalances = kind == PoolBalanceChangeKind.JOIN ? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts) : _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts); } /** * @dev Transfers `amountsIn` from `sender`, checking that they are within their accepted limits, and pays * accumulated protocol swap fees. * * Returns the Pool's final balances, which are the current balances plus `amountsIn` minus accumulated protocol * swap fees. */ function _processJoinPoolTransfers( address sender, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { // We need to track how much of the received ETH was used and wrapped into WETH to return any excess. uint256 wrappedEth = 0; finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountIn = amountsIn[i]; _require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX); // Receive assets from the sender - possibly from Internal Balance. IAsset asset = change.assets[i]; _receiveAsset(asset, amountIn, sender, change.useInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(amountIn); } uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); // Compute the new Pool balances. Note that the fee amount might be larger than `amountIn`, // resulting in an overall decrease of the Pool's balance for a token. finalBalances[i] = (amountIn >= feeAmount) // This lets us skip checked arithmetic ? balances[i].increaseCash(amountIn - feeAmount) : balances[i].decreaseCash(feeAmount - amountIn); } // Handle any used and remaining ETH. _handleRemainingEth(wrappedEth); } /** * @dev Transfers `amountsOut` to `recipient`, checking that they are within their accepted limits, and pays * accumulated protocol swap fees from the Pool. * * Returns the Pool's final balances, which are the current `balances` minus `amountsOut` and fees paid * (`dueProtocolFeeAmounts`). */ function _processExitPoolTransfers( address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountOut = amountsOut[i]; _require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN); // Send tokens to the recipient - possibly to Internal Balance IAsset asset = change.assets[i]; _sendAsset(asset, amountOut, recipient, change.useInternalBalance); uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); // Compute the new Pool balances. A Pool's token balance always decreases after an exit (potentially by 0). finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount)); } } /** * @dev Returns the total balance for `poolId`'s `expectedTokens`. * * `expectedTokens` must exactly equal the token array returned by `getPoolTokens`: both arrays must have the same * length, elements and order. Additionally, the Pool must have at least one registered token. */ function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens) private view returns (bytes32[] memory) { (IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId); InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length); _require(actualTokens.length > 0, Errors.POOL_NO_TOKENS); for (uint256 i = 0; i < actualTokens.length; ++i) { _require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH); } return balances; } /** * @dev Casts an array of uint256 to int256, setting the sign of the result according to the `positive` flag, * without checking whether the values fit in the signed 256 bit range. */ function _unsafeCastToInt256(uint256[] memory values, bool positive) private pure returns (int256[] memory signedValues) { signedValues = new int256[](values.length); for (uint256 i = 0; i < values.length; i++) { signedValues[i] = positive ? int256(values[i]) : -int256(values[i]); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/openzeppelin/IERC20.sol"; import "./IVault.sol"; interface IPoolSwapStructs { // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and // IMinimalSwapInfoPool. // // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or // 'given out') which indicates whether or not the amount sent by the pool is known. // // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. // // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in // some Pools. // // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than // one Pool. // // The meaning of `lastChangeBlock` depends on the Pool specialization: // - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total // balance. // - General: the last block in which *any* of the Pool's registered tokens changed its total balance. // // `from` is the origin address for the funds the Pool receives, and `to` is the destination address // where the Pool sends the outgoing tokens. // // `userData` is extra data provided by the caller - typically a signature from a trusted party. struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; // Misc data bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev IPools with the General specialization setting should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will * grant to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IGeneralPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256[] memory balances, uint256 indexIn, uint256 indexOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IBasePool.sol"; /** * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface. * * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool. * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant * to the pool in a 'given out' swap. * * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is * indeed the Vault. */ interface IMinimalSwapInfoPool is IBasePool { function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) external returns (uint256 amount); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/math/Math.sol"; // This library is used to create a data structure that represents a token's balance for a Pool. 'cash' is how many // tokens the Pool has sitting inside of the Vault. 'managed' is how many tokens were withdrawn from the Vault by the // Pool's Asset Manager. 'total' is the sum of these two, and represents the Pool's total token balance, including // tokens that are *not* inside of the Vault. // // 'cash' is updated whenever tokens enter and exit the Vault, while 'managed' is only updated if the reason tokens are // moving is due to an Asset Manager action. This is reflected in the different methods available: 'increaseCash' // and 'decreaseCash' for swaps and add/remove liquidity events, and 'cashToManaged' and 'managedToCash' for events // transferring funds to and from the Asset Manager. // // The Vault disallows the Pool's 'cash' from becoming negative. In other words, it can never use any tokens that are // not inside the Vault. // // One of the goals of this library is to store the entire token balance in a single storage slot, which is why we use // 112 bit unsigned integers for 'cash' and 'managed'. For consistency, we also disallow any combination of 'cash' and // 'managed' that yields a 'total' that doesn't fit in 112 bits. // // The remaining 32 bits of the slot are used to store the most recent block when the total balance changed. This // can be used to implement price oracles that are resilient to 'sandwich' attacks. // // We could use a Solidity struct to pack these three values together in a single storage slot, but unfortunately // Solidity only allows for structs to live in either storage, calldata or memory. Because a memory struct still takes // up a slot in the stack (to store its memory location), and because the entire balance fits in a single stack slot // (two 112 bit values plus the 32 bit block), using memory is strictly less gas performant. Therefore, we do manual // packing and unpacking. // // Since we cannot define new types, we rely on bytes32 to represent these values instead, as it doesn't have any // associated arithmetic operations and therefore reduces the chance of misuse. library BalanceAllocation { using Math for uint256; // The 'cash' portion of the balance is stored in the least significant 112 bits of a 256 bit word, while the // 'managed' part uses the following 112 bits. The most significant 32 bits are used to store the block /** * @dev Returns the total amount of Pool tokens, including those that are not currently in the Vault ('managed'). */ function total(bytes32 balance) internal pure returns (uint256) { // Since 'cash' and 'managed' are 112 bit values, we don't need checked arithmetic. Additionally, `toBalance` // ensures that 'total' always fits in 112 bits. return cash(balance) + managed(balance); } /** * @dev Returns the amount of Pool tokens currently in the Vault. */ function cash(bytes32 balance) internal pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(balance) & mask; } /** * @dev Returns the amount of Pool tokens that are being managed by an Asset Manager. */ function managed(bytes32 balance) internal pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(balance >> 112) & mask; } /** * @dev Returns the last block when the total balance changed. */ function lastChangeBlock(bytes32 balance) internal pure returns (uint256) { uint256 mask = 2**(32) - 1; return uint256(balance >> 224) & mask; } /** * @dev Returns the difference in 'managed' between two balances. */ function managedDelta(bytes32 newBalance, bytes32 oldBalance) internal pure returns (int256) { // Because `managed` is a 112 bit value, we can safely perform unchecked arithmetic in 256 bits. return int256(managed(newBalance)) - int256(managed(oldBalance)); } /** * @dev Returns the total balance for each entry in `balances`, as well as the latest block when the total * balance of *any* of them last changed. */ function totalsAndLastChangeBlock(bytes32[] memory balances) internal pure returns ( uint256[] memory results, uint256 lastChangeBlock_ // Avoid shadowing ) { results = new uint256[](balances.length); lastChangeBlock_ = 0; for (uint256 i = 0; i < results.length; i++) { bytes32 balance = balances[i]; results[i] = total(balance); lastChangeBlock_ = Math.max(lastChangeBlock_, lastChangeBlock(balance)); } } /** * @dev Returns true if `balance`'s 'total' balance is zero. Costs less gas than computing 'total' and comparing * with zero. */ function isZero(bytes32 balance) internal pure returns (bool) { // We simply need to check the least significant 224 bytes of the word: the block does not affect this. uint256 mask = 2**(224) - 1; return (uint256(balance) & mask) == 0; } /** * @dev Returns true if `balance`'s 'total' balance is not zero. Costs less gas than computing 'total' and comparing * with zero. */ function isNotZero(bytes32 balance) internal pure returns (bool) { return !isZero(balance); } /** * @dev Packs together `cash` and `managed` amounts with a block to create a balance value. * * For consistency, this also checks that the sum of `cash` and `managed` (`total`) fits in 112 bits. */ function toBalance( uint256 _cash, uint256 _managed, uint256 _blockNumber ) internal pure returns (bytes32) { uint256 _total = _cash + _managed; // Since both 'cash' and 'managed' are positive integers, by checking that their sum ('total') fits in 112 bits // we are also indirectly checking that both 'cash' and 'managed' themselves fit in 112 bits. _require(_total >= _cash && _total < 2**112, Errors.BALANCE_TOTAL_OVERFLOW); // We assume the block fits in 32 bits - this is expected to hold for at least a few decades. return _pack(_cash, _managed, _blockNumber); } /** * @dev Increases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent to the Vault (except * for Asset Manager deposits). * * Updates the last total balance change block, even if `amount` is zero. */ function increaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) { uint256 newCash = cash(balance).add(amount); uint256 currentManaged = managed(balance); uint256 newLastChangeBlock = block.number; return toBalance(newCash, currentManaged, newLastChangeBlock); } /** * @dev Decreases a Pool's 'cash' (and therefore its 'total'). Called when Pool tokens are sent from the Vault * (except for Asset Manager withdrawals). * * Updates the last total balance change block, even if `amount` is zero. */ function decreaseCash(bytes32 balance, uint256 amount) internal view returns (bytes32) { uint256 newCash = cash(balance).sub(amount); uint256 currentManaged = managed(balance); uint256 newLastChangeBlock = block.number; return toBalance(newCash, currentManaged, newLastChangeBlock); } /** * @dev Moves 'cash' into 'managed', leaving 'total' unchanged. Called when an Asset Manager withdraws Pool tokens * from the Vault. */ function cashToManaged(bytes32 balance, uint256 amount) internal pure returns (bytes32) { uint256 newCash = cash(balance).sub(amount); uint256 newManaged = managed(balance).add(amount); uint256 currentLastChangeBlock = lastChangeBlock(balance); return toBalance(newCash, newManaged, currentLastChangeBlock); } /** * @dev Moves 'managed' into 'cash', leaving 'total' unchanged. Called when an Asset Manager deposits Pool tokens * into the Vault. */ function managedToCash(bytes32 balance, uint256 amount) internal pure returns (bytes32) { uint256 newCash = cash(balance).add(amount); uint256 newManaged = managed(balance).sub(amount); uint256 currentLastChangeBlock = lastChangeBlock(balance); return toBalance(newCash, newManaged, currentLastChangeBlock); } /** * @dev Sets 'managed' balance to an arbitrary value, changing 'total'. Called when the Asset Manager reports * profits or losses. It's the Manager's responsibility to provide a meaningful value. * * Updates the last total balance change block, even if `newManaged` is equal to the current 'managed' value. */ function setManaged(bytes32 balance, uint256 newManaged) internal view returns (bytes32) { uint256 currentCash = cash(balance); uint256 newLastChangeBlock = block.number; return toBalance(currentCash, newManaged, newLastChangeBlock); } // Alternative mode for Pools with the Two Token specialization setting // Instead of storing cash and external for each 'token in' a single storage slot, Two Token Pools store the cash // for both tokens in the same slot, and the managed for both in another one. This reduces the gas cost for swaps, // because the only slot that needs to be updated is the one with the cash. However, it also means that managing // balances is more cumbersome, as both tokens need to be read/written at the same time. // // The field with both cash balances packed is called sharedCash, and the one with external amounts is called // sharedManaged. These two are collectively called the 'shared' balance fields. In both of these, the portion // that corresponds to token A is stored in the least significant 112 bits of a 256 bit word, while token B's part // uses the next least significant 112 bits. // // Because only cash is written to during a swap, we store the last total balance change block with the // packed cash fields. Typically Pools have a distinct block per token: in the case of Two Token Pools they // are the same. /** * @dev Extracts the part of the balance that corresponds to token A. This function can be used to decode both * shared cash and managed balances. */ function _decodeBalanceA(bytes32 sharedBalance) private pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(sharedBalance) & mask; } /** * @dev Extracts the part of the balance that corresponds to token B. This function can be used to decode both * shared cash and managed balances. */ function _decodeBalanceB(bytes32 sharedBalance) private pure returns (uint256) { uint256 mask = 2**(112) - 1; return uint256(sharedBalance >> 112) & mask; } // To decode the last balance change block, we can simply use the `blockNumber` function. /** * @dev Unpacks the shared token A and token B cash and managed balances into the balance for token A. */ function fromSharedToBalanceA(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) { // Note that we extract the block from the sharedCash field, which is the one that is updated by swaps. // Both token A and token B use the same block return toBalance(_decodeBalanceA(sharedCash), _decodeBalanceA(sharedManaged), lastChangeBlock(sharedCash)); } /** * @dev Unpacks the shared token A and token B cash and managed balances into the balance for token B. */ function fromSharedToBalanceB(bytes32 sharedCash, bytes32 sharedManaged) internal pure returns (bytes32) { // Note that we extract the block from the sharedCash field, which is the one that is updated by swaps. // Both token A and token B use the same block return toBalance(_decodeBalanceB(sharedCash), _decodeBalanceB(sharedManaged), lastChangeBlock(sharedCash)); } /** * @dev Returns the sharedCash shared field, given the current balances for token A and token B. */ function toSharedCash(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) { // Both balances are assigned the same block Since it is possible a single one of them has changed (for // example, in an Asset Manager update), we keep the latest (largest) one. uint32 newLastChangeBlock = uint32(Math.max(lastChangeBlock(tokenABalance), lastChangeBlock(tokenBBalance))); return _pack(cash(tokenABalance), cash(tokenBBalance), newLastChangeBlock); } /** * @dev Returns the sharedManaged shared field, given the current balances for token A and token B. */ function toSharedManaged(bytes32 tokenABalance, bytes32 tokenBBalance) internal pure returns (bytes32) { // We don't bother storing a last change block, as it is read from the shared cash field. return _pack(managed(tokenABalance), managed(tokenBBalance), 0); } // Shared functions /** * @dev Packs together two uint112 and one uint32 into a bytes32 */ function _pack( uint256 _leastSignificant, uint256 _midSignificant, uint256 _mostSignificant ) private pure returns (bytes32) { return bytes32((_mostSignificant << 224) + (_midSignificant << 112) + _leastSignificant); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./AssetManagers.sol"; import "./PoolRegistry.sol"; import "./balances/BalanceAllocation.sol"; abstract contract PoolTokens is ReentrancyGuard, PoolRegistry, AssetManagers { using BalanceAllocation for bytes32; using BalanceAllocation for bytes32[]; function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external override nonReentrant whenNotPaused onlyPool(poolId) { InputHelpers.ensureInputLengthMatch(tokens.length, assetManagers.length); // Validates token addresses and assigns Asset Managers for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; _require(token != IERC20(0), Errors.INVALID_TOKEN); _poolAssetManagers[poolId][token] = assetManagers[i]; } PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2); _registerTwoTokenPoolTokens(poolId, tokens[0], tokens[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _registerMinimalSwapInfoPoolTokens(poolId, tokens); } else { // PoolSpecialization.GENERAL _registerGeneralPoolTokens(poolId, tokens); } emit TokensRegistered(poolId, tokens, assetManagers); } function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external override nonReentrant whenNotPaused onlyPool(poolId) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _require(tokens.length == 2, Errors.TOKENS_LENGTH_MUST_BE_2); _deregisterTwoTokenPoolTokens(poolId, tokens[0], tokens[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _deregisterMinimalSwapInfoPoolTokens(poolId, tokens); } else { // PoolSpecialization.GENERAL _deregisterGeneralPoolTokens(poolId, tokens); } // The deregister calls above ensure the total token balance is zero. Therefore it is now safe to remove any // associated Asset Managers, since they hold no Pool balance. for (uint256 i = 0; i < tokens.length; ++i) { delete _poolAssetManagers[poolId][tokens[i]]; } emit TokensDeregistered(poolId, tokens); } function getPoolTokens(bytes32 poolId) external view override withRegisteredPool(poolId) returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ) { bytes32[] memory rawBalances; (tokens, rawBalances) = _getPoolTokens(poolId); (balances, lastChangeBlock) = rawBalances.totalsAndLastChangeBlock(); } function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view override withRegisteredPool(poolId) returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ) { bytes32 balance; PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { balance = _getTwoTokenPoolBalance(poolId, token); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { balance = _getMinimalSwapInfoPoolBalance(poolId, token); } else { // PoolSpecialization.GENERAL balance = _getGeneralPoolBalance(poolId, token); } cash = balance.cash(); managed = balance.managed(); lastChangeBlock = balance.lastChangeBlock(); assetManager = _poolAssetManagers[poolId][token]; } /** * @dev Returns all of `poolId`'s registered tokens, along with their raw balances. */ function _getPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { return _getTwoTokenPoolTokens(poolId); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { return _getMinimalSwapInfoPoolTokens(poolId); } else { // PoolSpecialization.GENERAL return _getGeneralPoolTokens(poolId); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/math/Math.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "../lib/openzeppelin/SafeCast.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "./AssetTransfersHandler.sol"; import "./VaultAuthorization.sol"; /** * Implement User Balance interactions, which combine Internal Balance and using the Vault's ERC20 allowance. * * Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later * transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination * when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced * gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. * * Internal Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different senders and recipients, at once. */ abstract contract UserBalance is ReentrancyGuard, AssetTransfersHandler, VaultAuthorization { using Math for uint256; using SafeCast for uint256; using SafeERC20 for IERC20; // Internal Balance for each token, for each account. mapping(address => mapping(IERC20 => uint256)) private _internalTokenBalance; function getInternalBalance(address user, IERC20[] memory tokens) external view override returns (uint256[] memory balances) { balances = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { balances[i] = _getInternalBalance(user, tokens[i]); } } function manageUserBalance(UserBalanceOp[] memory ops) external payable override nonReentrant { // We need to track how much of the received ETH was used and wrapped into WETH to return any excess. uint256 ethWrapped = 0; // Cache for these checks so we only perform them once (if at all). bool checkedCallerIsRelayer = false; bool checkedNotPaused = false; for (uint256 i = 0; i < ops.length; i++) { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; // This destructuring by calling `_validateUserBalanceOp` seems odd, but results in reduced bytecode size. (kind, asset, amount, sender, recipient, checkedCallerIsRelayer) = _validateUserBalanceOp( ops[i], checkedCallerIsRelayer ); if (kind == UserBalanceOpKind.WITHDRAW_INTERNAL) { // Internal Balance withdrawals can always be performed by an authorized account. _withdrawFromInternalBalance(asset, sender, recipient, amount); } else { // All other operations are blocked if the contract is paused. // We cache the result of the pause check and skip it for other operations in this same transaction // (if any). if (!checkedNotPaused) { _ensureNotPaused(); checkedNotPaused = true; } if (kind == UserBalanceOpKind.DEPOSIT_INTERNAL) { _depositToInternalBalance(asset, sender, recipient, amount); // Keep track of all ETH wrapped into WETH as part of a deposit. if (_isETH(asset)) { ethWrapped = ethWrapped.add(amount); } } else { // Transfers don't support ETH. _require(!_isETH(asset), Errors.CANNOT_USE_ETH_SENTINEL); IERC20 token = _asIERC20(asset); if (kind == UserBalanceOpKind.TRANSFER_INTERNAL) { _transferInternalBalance(token, sender, recipient, amount); } else { // TRANSFER_EXTERNAL _transferToExternalBalance(token, sender, recipient, amount); } } } } // Handle any remaining ETH. _handleRemainingEth(ethWrapped); } function _depositToInternalBalance( IAsset asset, address sender, address recipient, uint256 amount ) private { _increaseInternalBalance(recipient, _translateToIERC20(asset), amount); _receiveAsset(asset, amount, sender, false); } function _withdrawFromInternalBalance( IAsset asset, address sender, address payable recipient, uint256 amount ) private { // A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`. _decreaseInternalBalance(sender, _translateToIERC20(asset), amount, false); _sendAsset(asset, amount, recipient, false); } function _transferInternalBalance( IERC20 token, address sender, address recipient, uint256 amount ) private { // A partial decrease of Internal Balance is disallowed: `sender` must have the full `amount`. _decreaseInternalBalance(sender, token, amount, false); _increaseInternalBalance(recipient, token, amount); } function _transferToExternalBalance( IERC20 token, address sender, address recipient, uint256 amount ) private { if (amount > 0) { token.safeTransferFrom(sender, recipient, amount); emit ExternalBalanceTransfer(token, sender, recipient, amount); } } /** * @dev Increases `account`'s Internal Balance for `token` by `amount`. */ function _increaseInternalBalance( address account, IERC20 token, uint256 amount ) internal override { uint256 currentBalance = _getInternalBalance(account, token); uint256 newBalance = currentBalance.add(amount); _setInternalBalance(account, token, newBalance, amount.toInt256()); } /** * @dev Decreases `account`'s Internal Balance for `token` by `amount`. If `allowPartial` is true, this function * doesn't revert if `account` doesn't have enough balance, and sets it to zero and returns the deducted amount * instead. */ function _decreaseInternalBalance( address account, IERC20 token, uint256 amount, bool allowPartial ) internal override returns (uint256 deducted) { uint256 currentBalance = _getInternalBalance(account, token); _require(allowPartial || (currentBalance >= amount), Errors.INSUFFICIENT_INTERNAL_BALANCE); deducted = Math.min(currentBalance, amount); // By construction, `deducted` is lower or equal to `currentBalance`, so we don't need to use checked // arithmetic. uint256 newBalance = currentBalance - deducted; _setInternalBalance(account, token, newBalance, -(deducted.toInt256())); } /** * @dev Sets `account`'s Internal Balance for `token` to `newBalance`. * * Emits an `InternalBalanceChanged` event. This event includes `delta`, which is the amount the balance increased * (if positive) or decreased (if negative). To avoid reading the current balance in order to compute the delta, * this function relies on the caller providing it directly. */ function _setInternalBalance( address account, IERC20 token, uint256 newBalance, int256 delta ) private { _internalTokenBalance[account][token] = newBalance; emit InternalBalanceChanged(account, token, delta); } /** * @dev Returns `account`'s Internal Balance for `token`. */ function _getInternalBalance(address account, IERC20 token) internal view returns (uint256) { return _internalTokenBalance[account][token]; } /** * @dev Destructures a User Balance operation, validating that the contract caller is allowed to perform it. */ function _validateUserBalanceOp(UserBalanceOp memory op, bool checkedCallerIsRelayer) private view returns ( UserBalanceOpKind, IAsset, uint256, address, address payable, bool ) { // The only argument we need to validate is `sender`, which can only be either the contract caller, or a // relayer approved by `sender`. address sender = op.sender; if (sender != msg.sender) { // We need to check both that the contract caller is a relayer, and that `sender` approved them. // Because the relayer check is global (i.e. independent of `sender`), we cache that result and skip it for // other operations in this same transaction (if any). if (!checkedCallerIsRelayer) { _authenticateCaller(); checkedCallerIsRelayer = true; } _require(_hasApprovedRelayer(sender, msg.sender), Errors.USER_DOESNT_ALLOW_RELAYER); } return (op.kind, op.asset, op.amount, sender, op.recipient, checkedCallerIsRelayer); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IVault.sol"; import "./IPoolSwapStructs.sol"; /** * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from * either IGeneralPool or IMinimalSwapInfoPool */ interface IBasePool is IPoolSwapStructs { /** * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault. * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`. * * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join. * * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account * designated to receive any benefits (typically pool shares). `currentBalances` contains the total balances * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as minting pool shares. */ function onJoinPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts); /** * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`, * as well as collect the reported amount in protocol fees, which the Pool should calculate based on * `protocolSwapFeePercentage`. * * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share. * * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account * to which the Vault will send the proceeds. `currentBalances` contains the total token balances for each token * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return. * * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total * balance. * * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.) * * Contracts implementing this function should check that the caller is indeed the Vault before performing any * state-changing operations, such as burning pool shares. */ function onExitPool( bytes32 poolId, address sender, address recipient, uint256[] memory balances, uint256 lastChangeBlock, uint256 protocolSwapFeePercentage, bytes memory userData ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/helpers/InputHelpers.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./UserBalance.sol"; import "./balances/BalanceAllocation.sol"; import "./balances/GeneralPoolsBalance.sol"; import "./balances/MinimalSwapInfoPoolsBalance.sol"; import "./balances/TwoTokenPoolsBalance.sol"; abstract contract AssetManagers is ReentrancyGuard, GeneralPoolsBalance, MinimalSwapInfoPoolsBalance, TwoTokenPoolsBalance { using Math for uint256; using SafeERC20 for IERC20; // Stores the Asset Manager for each token of each Pool. mapping(bytes32 => mapping(IERC20 => address)) internal _poolAssetManagers; function managePoolBalance(PoolBalanceOp[] memory ops) external override nonReentrant whenNotPaused { // This variable could be declared inside the loop, but that causes the compiler to allocate memory on each // loop iteration, increasing gas costs. PoolBalanceOp memory op; for (uint256 i = 0; i < ops.length; ++i) { // By indexing the array only once, we don't spend extra gas in the same bounds check. op = ops[i]; bytes32 poolId = op.poolId; _ensureRegisteredPool(poolId); IERC20 token = op.token; _require(_isTokenRegistered(poolId, token), Errors.TOKEN_NOT_REGISTERED); _require(_poolAssetManagers[poolId][token] == msg.sender, Errors.SENDER_NOT_ASSET_MANAGER); PoolBalanceOpKind kind = op.kind; uint256 amount = op.amount; (int256 cashDelta, int256 managedDelta) = _performPoolManagementOperation(kind, poolId, token, amount); emit PoolBalanceManaged(poolId, msg.sender, token, cashDelta, managedDelta); } } /** * @dev Performs the `kind` Asset Manager operation on a Pool. * * Withdrawals will transfer `amount` tokens to the caller, deposits will transfer `amount` tokens from the caller, * and updates will set the managed balance to `amount`. * * Returns a tuple with the 'cash' and 'managed' balance deltas as a result of this call. */ function _performPoolManagementOperation( PoolBalanceOpKind kind, bytes32 poolId, IERC20 token, uint256 amount ) private returns (int256, int256) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (kind == PoolBalanceOpKind.WITHDRAW) { return _withdrawPoolBalance(poolId, specialization, token, amount); } else if (kind == PoolBalanceOpKind.DEPOSIT) { return _depositPoolBalance(poolId, specialization, token, amount); } else { // PoolBalanceOpKind.UPDATE return _updateManagedBalance(poolId, specialization, token, amount); } } /** * @dev Moves `amount` tokens from a Pool's 'cash' to 'managed' balance, and transfers them to the caller. * * Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary. */ function _withdrawPoolBalance( bytes32 poolId, PoolSpecialization specialization, IERC20 token, uint256 amount ) private returns (int256 cashDelta, int256 managedDelta) { if (specialization == PoolSpecialization.TWO_TOKEN) { _twoTokenPoolCashToManaged(poolId, token, amount); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _minimalSwapInfoPoolCashToManaged(poolId, token, amount); } else { // PoolSpecialization.GENERAL _generalPoolCashToManaged(poolId, token, amount); } if (amount > 0) { token.safeTransfer(msg.sender, amount); } // Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will // therefore always fit in a 256 bit integer. cashDelta = int256(-amount); managedDelta = int256(amount); } /** * @dev Moves `amount` tokens from a Pool's 'managed' to 'cash' balance, and transfers them from the caller. * * Returns the 'cash' and 'managed' balance deltas as a result of this call, which will be complementary. */ function _depositPoolBalance( bytes32 poolId, PoolSpecialization specialization, IERC20 token, uint256 amount ) private returns (int256 cashDelta, int256 managedDelta) { if (specialization == PoolSpecialization.TWO_TOKEN) { _twoTokenPoolManagedToCash(poolId, token, amount); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { _minimalSwapInfoPoolManagedToCash(poolId, token, amount); } else { // PoolSpecialization.GENERAL _generalPoolManagedToCash(poolId, token, amount); } if (amount > 0) { token.safeTransferFrom(msg.sender, address(this), amount); } // Since 'cash' and 'managed' are stored as uint112, `amount` is guaranteed to also fit in 112 bits. It will // therefore always fit in a 256 bit integer. cashDelta = int256(amount); managedDelta = int256(-amount); } /** * @dev Sets a Pool's 'managed' balance to `amount`. * * Returns the 'cash' and 'managed' balance deltas as a result of this call (the 'cash' delta will always be zero). */ function _updateManagedBalance( bytes32 poolId, PoolSpecialization specialization, IERC20 token, uint256 amount ) private returns (int256 cashDelta, int256 managedDelta) { if (specialization == PoolSpecialization.TWO_TOKEN) { managedDelta = _setTwoTokenPoolManagedBalance(poolId, token, amount); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { managedDelta = _setMinimalSwapInfoPoolManagedBalance(poolId, token, amount); } else { // PoolSpecialization.GENERAL managedDelta = _setGeneralPoolManagedBalance(poolId, token, amount); } cashDelta = 0; } /** * @dev Returns true if `token` is registered for `poolId`. */ function _isTokenRegistered(bytes32 poolId, IERC20 token) private view returns (bool) { PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { return _isTwoTokenPoolTokenRegistered(poolId, token); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { return _isMinimalSwapInfoPoolTokenRegistered(poolId, token); } else { // PoolSpecialization.GENERAL return _isGeneralPoolTokenRegistered(poolId, token); } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/ReentrancyGuard.sol"; import "./VaultAuthorization.sol"; /** * @dev Maintains the Pool ID data structure, implements Pool ID creation and registration, and defines useful modifiers * and helper functions for ensuring correct behavior when working with Pools. */ abstract contract PoolRegistry is ReentrancyGuard, VaultAuthorization { // Each pool is represented by their unique Pool ID. We use `bytes32` for them, for lack of a way to define new // types. mapping(bytes32 => bool) private _isPoolRegistered; // We keep an increasing nonce to make Pool IDs unique. It is interpreted as a `uint80`, but storing it as a // `uint256` results in reduced bytecode on reads and writes due to the lack of masking. uint256 private _nextPoolNonce; /** * @dev Reverts unless `poolId` corresponds to a registered Pool. */ modifier withRegisteredPool(bytes32 poolId) { _ensureRegisteredPool(poolId); _; } /** * @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract. */ modifier onlyPool(bytes32 poolId) { _ensurePoolIsSender(poolId); _; } /** * @dev Reverts unless `poolId` corresponds to a registered Pool. */ function _ensureRegisteredPool(bytes32 poolId) internal view { _require(_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); } /** * @dev Reverts unless `poolId` corresponds to a registered Pool, and the caller is the Pool's contract. */ function _ensurePoolIsSender(bytes32 poolId) private view { _ensureRegisteredPool(poolId); _require(msg.sender == _getPoolAddress(poolId), Errors.CALLER_NOT_POOL); } function registerPool(PoolSpecialization specialization) external override nonReentrant whenNotPaused returns (bytes32) { // Each Pool is assigned a unique ID based on an incrementing nonce. This assumes there will never be more than // 2**80 Pools, and the nonce will not overflow. bytes32 poolId = _toPoolId(msg.sender, specialization, uint80(_nextPoolNonce)); _require(!_isPoolRegistered[poolId], Errors.INVALID_POOL_ID); // Should never happen as Pool IDs are unique. _isPoolRegistered[poolId] = true; _nextPoolNonce += 1; // Note that msg.sender is the pool's contract emit PoolRegistered(poolId, msg.sender, specialization); return poolId; } function getPool(bytes32 poolId) external view override withRegisteredPool(poolId) returns (address, PoolSpecialization) { return (_getPoolAddress(poolId), _getPoolSpecialization(poolId)); } /** * @dev Creates a Pool ID. * * These are deterministically created by packing the Pool's contract address and its specialization setting into * the ID. This saves gas by making this data easily retrievable from a Pool ID with no storage accesses. * * Since a single contract can register multiple Pools, a unique nonce must be provided to ensure Pool IDs are * unique. * * Pool IDs have the following layout: * | 20 bytes pool contract address | 2 bytes specialization setting | 10 bytes nonce | * MSB LSB * * 2 bytes for the specialization setting is a bit overkill: there only three of them, which means two bits would * suffice. However, there's nothing else of interest to store in this extra space. */ function _toPoolId( address pool, PoolSpecialization specialization, uint80 nonce ) internal pure returns (bytes32) { bytes32 serialized; serialized |= bytes32(uint256(nonce)); serialized |= bytes32(uint256(specialization)) << (10 * 8); serialized |= bytes32(uint256(pool)) << (12 * 8); return serialized; } /** * @dev Returns the address of a Pool's contract. * * Due to how Pool IDs are created, this is done with no storage accesses and costs little gas. */ function _getPoolAddress(bytes32 poolId) internal pure returns (address) { // 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask, // since the logical shift already sets the upper bits to zero. return address(uint256(poolId) >> (12 * 8)); } /** * @dev Returns the specialization setting of a Pool. * * Due to how Pool IDs are created, this is done with no storage accesses and costs little gas. */ function _getPoolSpecialization(bytes32 poolId) internal pure returns (PoolSpecialization specialization) { // 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address. uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1); // Casting a value into an enum results in a runtime check that reverts unless the value is within the enum's // range. Passing an invalid Pool ID to this function would then result in an obscure revert with no reason // string: we instead perform the check ourselves to help in error diagnosis. // There are three Pool specialization settings: general, minimal swap info and two tokens, which correspond to // values 0, 1 and 2. _require(value < 3, Errors.INVALID_POOL_ID); // Because we have checked that `value` is within the enum range, we can use assembly to skip the runtime check. // solhint-disable-next-line no-inline-assembly assembly { specialization := value } } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../../lib/helpers/BalancerErrors.sol"; import "../../lib/openzeppelin/EnumerableMap.sol"; import "../../lib/openzeppelin/IERC20.sol"; import "./BalanceAllocation.sol"; abstract contract GeneralPoolsBalance { using BalanceAllocation for bytes32; using EnumerableMap for EnumerableMap.IERC20ToBytes32Map; // Data for Pools with the General specialization setting // // These Pools use the IGeneralPool interface, which means the Vault must query the balance for *all* of their // tokens in every swap. If we kept a mapping of token to balance plus a set (array) of tokens, it'd be very gas // intensive to read all token addresses just to then do a lookup on the balance mapping. // // Instead, we use our customized EnumerableMap, which lets us read the N balances in N+1 storage accesses (one for // each token in the Pool), access the index of any 'token in' a single read (required for the IGeneralPool call), // and update an entry's value given its index. // Map of token -> balance pairs for each Pool with this specialization. Many functions rely on storage pointers to // a Pool's EnumerableMap to save gas when computing storage slots. mapping(bytes32 => EnumerableMap.IERC20ToBytes32Map) internal _generalPoolsBalances; /** * @dev Registers a list of tokens in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * Requirements: * * - `tokens` must not be registered in the Pool * - `tokens` must not contain duplicates */ function _registerGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { // EnumerableMaps require an explicit initial value when creating a key-value pair: we use zero, the same // value that is found in uninitialized storage, which corresponds to an empty balance. bool added = poolBalances.set(tokens[i], 0); _require(added, Errors.TOKEN_ALREADY_REGISTERED); } } /** * @dev Deregisters a list of tokens in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * Requirements: * * - `tokens` must be registered in the Pool * - `tokens` must have zero balance in the Vault * - `tokens` must not contain duplicates */ function _deregisterGeneralPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token); _require(currentBalance.isZero(), Errors.NONZERO_TOKEN_BALANCE); // We don't need to check remove's return value, since _getGeneralPoolBalance already checks that the token // was registered. poolBalances.remove(token); } } /** * @dev Sets the balances of a General Pool's tokens to `balances`. * * WARNING: this assumes `balances` has the same length and order as the Pool's tokens. */ function _setGeneralPoolBalances(bytes32 poolId, bytes32[] memory balances) internal { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; for (uint256 i = 0; i < balances.length; ++i) { // Since we assume all balances are properly ordered, we can simply use `unchecked_setAt` to avoid one less // storage read per token. poolBalances.unchecked_setAt(i, balances[i]); } } /** * @dev Transforms `amount` of `token`'s balance in a General Pool from cash into managed. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. */ function _generalPoolCashToManaged( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateGeneralPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount); } /** * @dev Transforms `amount` of `token`'s balance in a General Pool from managed into cash. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. */ function _generalPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateGeneralPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount); } /** * @dev Sets `token`'s managed balance in a General Pool to `amount`. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _setGeneralPoolManagedBalance( bytes32 poolId, IERC20 token, uint256 amount ) internal returns (int256) { return _updateGeneralPoolBalance(poolId, token, BalanceAllocation.setManaged, amount); } /** * @dev Sets `token`'s balance in a General Pool to the result of the `mutation` function when called with the * current balance and `amount`. * * This function assumes `poolId` exists, corresponds to the General specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _updateGeneralPoolBalance( bytes32 poolId, IERC20 token, function(bytes32, uint256) returns (bytes32) mutation, uint256 amount ) private returns (int256) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; bytes32 currentBalance = _getGeneralPoolBalance(poolBalances, token); bytes32 newBalance = mutation(currentBalance, amount); poolBalances.set(token, newBalance); return newBalance.managedDelta(currentBalance); } /** * @dev Returns an array with all the tokens and balances in a General Pool. The order may change when tokens are * registered or deregistered. * * This function assumes `poolId` exists and corresponds to the General specialization setting. */ function _getGeneralPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; tokens = new IERC20[](poolBalances.length()); balances = new bytes32[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { // Because the iteration is bounded by `tokens.length`, which matches the EnumerableMap's length, we can use // `unchecked_at` as we know `i` is a valid token index, saving storage reads. (tokens[i], balances[i]) = poolBalances.unchecked_at(i); } } /** * @dev Returns the balance of a token in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * Requirements: * * - `token` must be registered in the Pool */ function _getGeneralPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; return _getGeneralPoolBalance(poolBalances, token); } /** * @dev Same as `_getGeneralPoolBalance` but using a Pool's storage pointer, which saves gas in repeated reads and * writes. */ function _getGeneralPoolBalance(EnumerableMap.IERC20ToBytes32Map storage poolBalances, IERC20 token) private view returns (bytes32) { return poolBalances.get(token, Errors.TOKEN_NOT_REGISTERED); } /** * @dev Returns true if `token` is registered in a General Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. */ function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; return poolBalances.contains(token); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/BalancerErrors.sol"; import "../../lib/openzeppelin/EnumerableSet.sol"; import "../../lib/openzeppelin/IERC20.sol"; import "./BalanceAllocation.sol"; import "../PoolRegistry.sol"; abstract contract MinimalSwapInfoPoolsBalance is PoolRegistry { using BalanceAllocation for bytes32; using EnumerableSet for EnumerableSet.AddressSet; // Data for Pools with the Minimal Swap Info specialization setting // // These Pools use the IMinimalSwapInfoPool interface, and so the Vault must read the balance of the two tokens // in the swap. The best solution is to use a mapping from token to balance, which lets us read or write any token's // balance in a single storage access. // // We also keep a set of registered tokens. Because tokens with non-zero balance are by definition registered, in // some balance getters we skip checking for token registration if a non-zero balance is found, saving gas by // performing a single read instead of two. mapping(bytes32 => mapping(IERC20 => bytes32)) internal _minimalSwapInfoPoolsBalances; mapping(bytes32 => EnumerableSet.AddressSet) internal _minimalSwapInfoPoolsTokens; /** * @dev Registers a list of tokens in a Minimal Swap Info Pool. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. * * Requirements: * * - `tokens` must not be registered in the Pool * - `tokens` must not contain duplicates */ function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { bool added = poolTokens.add(address(tokens[i])); _require(added, Errors.TOKEN_ALREADY_REGISTERED); // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty // balance. } } /** * @dev Deregisters a list of tokens in a Minimal Swap Info Pool. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. * * Requirements: * * - `tokens` must be registered in the Pool * - `tokens` must have zero balance in the Vault * - `tokens` must not contain duplicates */ function _deregisterMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { IERC20 token = tokens[i]; _require(_minimalSwapInfoPoolsBalances[poolId][token].isZero(), Errors.NONZERO_TOKEN_BALANCE); // For consistency with other Pool specialization settings, we explicitly reset the balance (which may have // a non-zero last change block). delete _minimalSwapInfoPoolsBalances[poolId][token]; bool removed = poolTokens.remove(address(token)); _require(removed, Errors.TOKEN_NOT_REGISTERED); } } /** * @dev Sets the balances of a Minimal Swap Info Pool's tokens to `balances`. * * WARNING: this assumes `balances` has the same length and order as the Pool's tokens. */ function _setMinimalSwapInfoPoolBalances( bytes32 poolId, IERC20[] memory tokens, bytes32[] memory balances ) internal { for (uint256 i = 0; i < tokens.length; ++i) { _minimalSwapInfoPoolsBalances[poolId][tokens[i]] = balances[i]; } } /** * @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from cash into managed. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. */ function _minimalSwapInfoPoolCashToManaged( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.cashToManaged, amount); } /** * @dev Transforms `amount` of `token`'s balance in a Minimal Swap Info Pool from managed into cash. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. */ function _minimalSwapInfoPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.managedToCash, amount); } /** * @dev Sets `token`'s managed balance in a Minimal Swap Info Pool to `amount`. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _setMinimalSwapInfoPoolManagedBalance( bytes32 poolId, IERC20 token, uint256 amount ) internal returns (int256) { return _updateMinimalSwapInfoPoolBalance(poolId, token, BalanceAllocation.setManaged, amount); } /** * @dev Sets `token`'s balance in a Minimal Swap Info Pool to the result of the `mutation` function when called with * the current balance and `amount`. * * This function assumes `poolId` exists, corresponds to the Minimal Swap Info specialization setting, and that * `token` is registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _updateMinimalSwapInfoPoolBalance( bytes32 poolId, IERC20 token, function(bytes32, uint256) returns (bytes32) mutation, uint256 amount ) internal returns (int256) { bytes32 currentBalance = _getMinimalSwapInfoPoolBalance(poolId, token); bytes32 newBalance = mutation(currentBalance, amount); _minimalSwapInfoPoolsBalances[poolId][token] = newBalance; return newBalance.managedDelta(currentBalance); } /** * @dev Returns an array with all the tokens and balances in a Minimal Swap Info Pool. The order may change when * tokens are registered or deregistered. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. */ function _getMinimalSwapInfoPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; tokens = new IERC20[](poolTokens.length()); balances = new bytes32[](tokens.length); for (uint256 i = 0; i < tokens.length; ++i) { // Because the iteration is bounded by `tokens.length`, which matches the EnumerableSet's length, we can use // `unchecked_at` as we know `i` is a valid token index, saving storage reads. IERC20 token = IERC20(poolTokens.unchecked_at(i)); tokens[i] = token; balances[i] = _minimalSwapInfoPoolsBalances[poolId][token]; } } /** * @dev Returns the balance of a token in a Minimal Swap Info Pool. * * Requirements: * * - `poolId` must be a Minimal Swap Info Pool * - `token` must be registered in the Pool */ function _getMinimalSwapInfoPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) { bytes32 balance = _minimalSwapInfoPoolsBalances[poolId][token]; // A non-zero balance guarantees that the token is registered. If zero, we manually check if the token is // registered in the Pool. Token registration implies that the Pool is registered as well, which lets us save // gas by not performing the check. bool tokenRegistered = balance.isNotZero() || _minimalSwapInfoPoolsTokens[poolId].contains(address(token)); if (!tokenRegistered) { // The token might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(poolId); _revert(Errors.TOKEN_NOT_REGISTERED); } return balance; } /** * @dev Returns true if `token` is registered in a Minimal Swap Info Pool. * * This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. */ function _isMinimalSwapInfoPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; return poolTokens.contains(address(token)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../lib/helpers/BalancerErrors.sol"; import "../../lib/openzeppelin/IERC20.sol"; import "./BalanceAllocation.sol"; import "../PoolRegistry.sol"; abstract contract TwoTokenPoolsBalance is PoolRegistry { using BalanceAllocation for bytes32; // Data for Pools with the Two Token specialization setting // // These are similar to the Minimal Swap Info Pool case (because the Pool only has two tokens, and therefore there // are only two balances to read), but there's a key difference in how data is stored. Keeping a set makes little // sense, as it will only ever hold two tokens, so we can just store those two directly. // // The gas savings associated with using these Pools come from how token balances are stored: cash amounts for token // A and token B are packed together, as are managed amounts. Because only cash changes in a swap, there's no need // to write to this second storage slot. A single last change block number for both tokens is stored with the packed // cash fields. struct TwoTokenPoolBalances { bytes32 sharedCash; bytes32 sharedManaged; } // We could just keep a mapping from Pool ID to TwoTokenSharedBalances, but there's an issue: we wouldn't know to // which tokens those balances correspond. This would mean having to also check which are registered with the Pool. // // What we do instead to save those storage reads is keep a nested mapping from the token pair hash to the balances // struct. The Pool only has two tokens, so only a single entry of this mapping is set (the one that corresponds to // that pair's hash). // // This has the trade-off of making Vault code that interacts with these Pools cumbersome: both balances must be // accessed at the same time by using both token addresses, and some logic is needed to determine how the pair hash // is computed. We do this by sorting the tokens, calling the token with the lowest numerical address value token A, // and the other one token B. In functions where the token arguments could be either A or B, we use X and Y instead. // // If users query a token pair containing an unregistered token, the Pool will generate a hash for a mapping entry // that was not set, and return zero balances. Non-zero balances are only possible if both tokens in the pair // are registered with the Pool, which means we don't have to check the TwoTokenPoolTokens struct, and can save // storage reads. struct TwoTokenPoolTokens { IERC20 tokenA; IERC20 tokenB; mapping(bytes32 => TwoTokenPoolBalances) balances; } mapping(bytes32 => TwoTokenPoolTokens) private _twoTokenPoolTokens; /** * @dev Registers tokens in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. * * Requirements: * * - `tokenX` and `tokenY` must not be the same * - The tokens must be ordered: tokenX < tokenY */ function _registerTwoTokenPoolTokens( bytes32 poolId, IERC20 tokenX, IERC20 tokenY ) internal { // Not technically true since we didn't register yet, but this is consistent with the error messages of other // specialization settings. _require(tokenX != tokenY, Errors.TOKEN_ALREADY_REGISTERED); _require(tokenX < tokenY, Errors.UNSORTED_TOKENS); // A Two Token Pool with no registered tokens is identified by having zero addresses for tokens A and B. TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId]; _require(poolTokens.tokenA == IERC20(0) && poolTokens.tokenB == IERC20(0), Errors.TOKENS_ALREADY_SET); // Since tokenX < tokenY, tokenX is A and tokenY is B poolTokens.tokenA = tokenX; poolTokens.tokenB = tokenY; // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty // balance. } /** * @dev Deregisters tokens in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. * * Requirements: * * - `tokenX` and `tokenY` must be registered in the Pool * - both tokens must have zero balance in the Vault */ function _deregisterTwoTokenPoolTokens( bytes32 poolId, IERC20 tokenX, IERC20 tokenY ) internal { ( bytes32 balanceA, bytes32 balanceB, TwoTokenPoolBalances storage poolBalances ) = _getTwoTokenPoolSharedBalances(poolId, tokenX, tokenY); _require(balanceA.isZero() && balanceB.isZero(), Errors.NONZERO_TOKEN_BALANCE); delete _twoTokenPoolTokens[poolId]; // For consistency with other Pool specialization settings, we explicitly reset the packed cash field (which may // have a non-zero last change block). delete poolBalances.sharedCash; } /** * @dev Sets the cash balances of a Two Token Pool's tokens. * * WARNING: this assumes `tokenA` and `tokenB` are the Pool's two registered tokens, and are in the correct order. */ function _setTwoTokenPoolCashBalances( bytes32 poolId, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB ) internal { bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB); TwoTokenPoolBalances storage poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash]; poolBalances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB); } /** * @dev Transforms `amount` of `token`'s balance in a Two Token Pool from cash into managed. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. */ function _twoTokenPoolCashToManaged( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.cashToManaged, amount); } /** * @dev Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. */ function _twoTokenPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount ) internal { _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.managedToCash, amount); } /** * @dev Sets `token`'s managed balance in a Two Token Pool to `amount`. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _setTwoTokenPoolManagedBalance( bytes32 poolId, IERC20 token, uint256 amount ) internal returns (int256) { return _updateTwoTokenPoolSharedBalance(poolId, token, BalanceAllocation.setManaged, amount); } /** * @dev Sets `token`'s balance in a Two Token Pool to the result of the `mutation` function when called with * the current balance and `amount`. * * This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` is * registered for that Pool. * * Returns the managed balance delta as a result of this call. */ function _updateTwoTokenPoolSharedBalance( bytes32 poolId, IERC20 token, function(bytes32, uint256) returns (bytes32) mutation, uint256 amount ) private returns (int256) { ( TwoTokenPoolBalances storage balances, IERC20 tokenA, bytes32 balanceA, , bytes32 balanceB ) = _getTwoTokenPoolBalances(poolId); int256 delta; if (token == tokenA) { bytes32 newBalance = mutation(balanceA, amount); delta = newBalance.managedDelta(balanceA); balanceA = newBalance; } else { // token == tokenB bytes32 newBalance = mutation(balanceB, amount); delta = newBalance.managedDelta(balanceB); balanceB = newBalance; } balances.sharedCash = BalanceAllocation.toSharedCash(balanceA, balanceB); balances.sharedManaged = BalanceAllocation.toSharedManaged(balanceA, balanceB); return delta; } /* * @dev Returns an array with all the tokens and balances in a Two Token Pool. The order may change when * tokens are registered or deregistered. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. */ function _getTwoTokenPoolTokens(bytes32 poolId) internal view returns (IERC20[] memory tokens, bytes32[] memory balances) { (, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId); // Both tokens will either be zero (if unregistered) or non-zero (if registered), but we keep the full check for // clarity. if (tokenA == IERC20(0) || tokenB == IERC20(0)) { return (new IERC20[](0), new bytes32[](0)); } // Note that functions relying on this getter expect tokens to be properly ordered, so we use the (A, B) // ordering. tokens = new IERC20[](2); tokens[0] = tokenA; tokens[1] = tokenB; balances = new bytes32[](2); balances[0] = balanceA; balances[1] = balanceB; } /** * @dev Same as `_getTwoTokenPoolTokens`, except it returns the two tokens and balances directly instead of using * an array, as well as a storage pointer to the `TwoTokenPoolBalances` struct, which can be used to update it * without having to recompute the pair hash and storage slot. */ function _getTwoTokenPoolBalances(bytes32 poolId) private view returns ( TwoTokenPoolBalances storage poolBalances, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB ) { TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId]; tokenA = poolTokens.tokenA; tokenB = poolTokens.tokenB; bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB); poolBalances = poolTokens.balances[pairHash]; bytes32 sharedCash = poolBalances.sharedCash; bytes32 sharedManaged = poolBalances.sharedManaged; balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged); balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged); } /** * @dev Returns the balance of a token in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the General specialization setting. * * This function is convenient but not particularly gas efficient, and should be avoided during gas-sensitive * operations, such as swaps. For those, _getTwoTokenPoolSharedBalances provides a more flexible interface. * * Requirements: * * - `token` must be registered in the Pool */ function _getTwoTokenPoolBalance(bytes32 poolId, IERC20 token) internal view returns (bytes32) { // We can't just read the balance of token, because we need to know the full pair in order to compute the pair // hash and access the balance mapping. We therefore rely on `_getTwoTokenPoolBalances`. (, IERC20 tokenA, bytes32 balanceA, IERC20 tokenB, bytes32 balanceB) = _getTwoTokenPoolBalances(poolId); if (token == tokenA) { return balanceA; } else if (token == tokenB) { return balanceB; } else { _revert(Errors.TOKEN_NOT_REGISTERED); } } /** * @dev Returns the balance of the two tokens in a Two Token Pool. * * The returned balances are those of token A and token B, where token A is the lowest of token X and token Y, and * token B the other. * * This function also returns a storage pointer to the TwoTokenPoolBalances struct associated with the token pair, * which can be used to update it without having to recompute the pair hash and storage slot. * * Requirements: * * - `poolId` must be a Minimal Swap Info Pool * - `tokenX` and `tokenY` must be registered in the Pool */ function _getTwoTokenPoolSharedBalances( bytes32 poolId, IERC20 tokenX, IERC20 tokenY ) internal view returns ( bytes32 balanceA, bytes32 balanceB, TwoTokenPoolBalances storage poolBalances ) { (IERC20 tokenA, IERC20 tokenB) = _sortTwoTokens(tokenX, tokenY); bytes32 pairHash = _getTwoTokenPairHash(tokenA, tokenB); poolBalances = _twoTokenPoolTokens[poolId].balances[pairHash]; // Because we're reading balances using the pair hash, if either token X or token Y is not registered then // *both* balance entries will be zero. bytes32 sharedCash = poolBalances.sharedCash; bytes32 sharedManaged = poolBalances.sharedManaged; // A non-zero balance guarantees that both tokens are registered. If zero, we manually check whether each // token is registered in the Pool. Token registration implies that the Pool is registered as well, which // lets us save gas by not performing the check. bool tokensRegistered = sharedCash.isNotZero() || sharedManaged.isNotZero() || (_isTwoTokenPoolTokenRegistered(poolId, tokenA) && _isTwoTokenPoolTokenRegistered(poolId, tokenB)); if (!tokensRegistered) { // The tokens might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(poolId); _revert(Errors.TOKEN_NOT_REGISTERED); } balanceA = BalanceAllocation.fromSharedToBalanceA(sharedCash, sharedManaged); balanceB = BalanceAllocation.fromSharedToBalanceB(sharedCash, sharedManaged); } /** * @dev Returns true if `token` is registered in a Two Token Pool. * * This function assumes `poolId` exists and corresponds to the Two Token specialization setting. */ function _isTwoTokenPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { TwoTokenPoolTokens storage poolTokens = _twoTokenPoolTokens[poolId]; // The zero address can never be a registered token. return (token == poolTokens.tokenA || token == poolTokens.tokenB) && token != IERC20(0); } /** * @dev Returns the hash associated with a given token pair. */ function _getTwoTokenPairHash(IERC20 tokenA, IERC20 tokenB) private pure returns (bytes32) { return keccak256(abi.encodePacked(tokenA, tokenB)); } /** * @dev Sorts two tokens in ascending order, returning them as a (tokenA, tokenB) tuple. */ function _sortTwoTokens(IERC20 tokenX, IERC20 tokenY) private pure returns (IERC20, IERC20) { return tokenX < tokenY ? (tokenX, tokenY) : (tokenY, tokenX); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../lib/math/Math.sol"; import "../lib/helpers/BalancerErrors.sol"; import "../lib/openzeppelin/IERC20.sol"; import "../lib/helpers/AssetHelpers.sol"; import "../lib/openzeppelin/SafeERC20.sol"; import "../lib/openzeppelin/Address.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IAsset.sol"; import "./interfaces/IVault.sol"; abstract contract AssetTransfersHandler is AssetHelpers { using SafeERC20 for IERC20; using Address for address payable; /** * @dev Receives `amount` of `asset` from `sender`. If `fromInternalBalance` is true, it first withdraws as much * as possible from Internal Balance, then transfers any remaining amount. * * If `asset` is ETH, `fromInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds * will be wrapped into WETH. * * WARNING: this function does not check that the contract caller has actually supplied any ETH - it is up to the * caller of this function to check that this is true to prevent the Vault from using its own ETH (though the Vault * typically doesn't hold any). */ function _receiveAsset( IAsset asset, uint256 amount, address sender, bool fromInternalBalance ) internal { if (amount == 0) { return; } if (_isETH(asset)) { _require(!fromInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE); // The ETH amount to receive is deposited into the WETH contract, which will in turn mint WETH for // the Vault at a 1:1 ratio. // A check for this condition is also introduced by the compiler, but this one provides a revert reason. // Note we're checking for the Vault's total balance, *not* ETH sent in this transaction. _require(address(this).balance >= amount, Errors.INSUFFICIENT_ETH); _WETH().deposit{ value: amount }(); } else { IERC20 token = _asIERC20(asset); if (fromInternalBalance) { // We take as many tokens from Internal Balance as possible: any remaining amounts will be transferred. uint256 deductedBalance = _decreaseInternalBalance(sender, token, amount, true); // Because `deductedBalance` will be always the lesser of the current internal balance // and the amount to decrease, it is safe to perform unchecked arithmetic. amount -= deductedBalance; } if (amount > 0) { token.safeTransferFrom(sender, address(this), amount); } } } /** * @dev Sends `amount` of `asset` to `recipient`. If `toInternalBalance` is true, the asset is deposited as Internal * Balance instead of being transferred. * * If `asset` is ETH, `toInternalBalance` must be false (as ETH cannot be held as internal balance), and the funds * are instead sent directly after unwrapping WETH. */ function _sendAsset( IAsset asset, uint256 amount, address payable recipient, bool toInternalBalance ) internal { if (amount == 0) { return; } if (_isETH(asset)) { // Sending ETH is not as involved as receiving it: the only special behavior is it cannot be // deposited to Internal Balance. _require(!toInternalBalance, Errors.INVALID_ETH_INTERNAL_BALANCE); // First, the Vault withdraws deposited ETH from the WETH contract, by burning the same amount of WETH // from the Vault. This receipt will be handled by the Vault's `receive`. _WETH().withdraw(amount); // Then, the withdrawn ETH is sent to the recipient. recipient.sendValue(amount); } else { IERC20 token = _asIERC20(asset); if (toInternalBalance) { _increaseInternalBalance(recipient, token, amount); } else { token.safeTransfer(recipient, amount); } } } /** * @dev Returns excess ETH back to the contract caller, assuming `amountUsed` has been spent. Reverts * if the caller sent less ETH than `amountUsed`. * * Because the caller might not know exactly how much ETH a Vault action will require, they may send extra. * Note that this excess value is returned *to the contract caller* (msg.sender). If caller and e.g. swap sender are * not the same (because the caller is a relayer for the sender), then it is up to the caller to manage this * returned ETH. */ function _handleRemainingEth(uint256 amountUsed) internal { _require(msg.value >= amountUsed, Errors.INSUFFICIENT_ETH); uint256 excess = msg.value - amountUsed; if (excess > 0) { msg.sender.sendValue(excess); } } /** * @dev Enables the Vault to receive ETH. This is required for it to be able to unwrap WETH, which sends ETH to the * caller. * * Any ETH sent to the Vault outside of the WETH unwrapping mechanism would be forever locked inside the Vault, so * we prevent that from happening. Other mechanisms used to send ETH to the Vault (such as being the recipient of an * ETH swap, Pool exit or withdrawal, contract self-destruction, or receiving the block mining reward) will result * in locked funds, but are not otherwise a security or soundness issue. This check only exists as an attempt to * prevent user error. */ receive() external payable { _require(msg.sender == address(_WETH()), Errors.ETH_TRANSFER); } // This contract uses virtual internal functions instead of inheriting from the modules that implement them (in // this case UserBalance) in order to decouple it from the rest of the system and enable standalone testing by // implementing these with mocks. function _increaseInternalBalance( address account, IERC20 token, uint256 amount ) internal virtual; function _decreaseInternalBalance( address account, IERC20 token, uint256 amount, bool capped ) internal virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; import "../../vault/interfaces/IAsset.sol"; import "../../vault/interfaces/IWETH.sol"; abstract contract AssetHelpers { // solhint-disable-next-line var-name-mixedcase IWETH private immutable _weth; // Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for // multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and // it is an address Pools cannot register as a token. address private constant _ETH = address(0); constructor(IWETH weth) { _weth = weth; } // solhint-disable-next-line func-name-mixedcase function _WETH() internal view returns (IWETH) { return _weth; } /** * @dev Returns true if `asset` is the sentinel value that represents ETH. */ function _isETH(IAsset asset) internal pure returns (bool) { return address(asset) == _ETH; } /** * @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated * to the WETH contract. */ function _translateToIERC20(IAsset asset) internal view returns (IERC20) { return _isETH(asset) ? _WETH() : _asIERC20(asset); } /** * @dev Same as `_translateToIERC20(IAsset)`, but for an entire array. */ function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) { IERC20[] memory tokens = new IERC20[](assets.length); for (uint256 i = 0; i < assets.length; ++i) { tokens[i] = _translateToIERC20(assets[i]); } return tokens; } /** * @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously * returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value. */ function _asIERC20(IAsset asset) internal pure returns (IERC20) { return IERC20(address(asset)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // 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, Errors.ADDRESS_INSUFFICIENT_BALANCE); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); _require(success, Errors.ADDRESS_CANNOT_SEND_VALUE); } }
* @dev Returns true if the key is in the map. O(1)./
function contains(IERC20ToBytes32Map storage map, IERC20 key) internal view returns (bool) { return map._indexes[key] != 0; }
642,105
[ 1, 1356, 638, 309, 326, 498, 353, 316, 326, 852, 18, 531, 12, 21, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1914, 12, 45, 654, 39, 3462, 21033, 1578, 863, 2502, 852, 16, 467, 654, 39, 3462, 498, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 852, 6315, 11265, 63, 856, 65, 480, 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, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract mapping(address => bool) registeredAirline; mapping(address => uint256) airlineVotes; uint256 M ; event AirlineRegistered(string airline); event InsuranceStatus(string msg, uint val); event AirlineFunded(string msg); event Log(uint256 valDiv, uint256 valN, uint256 valM, address airline,bool status); event RegisteringAirline(string msg); FlightSuretyData flightSuretyData; /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(flightSuretyData.isOperational(),"Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address flightSuretyDataContract) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(flightSuretyDataContract); registeredAirline[contractOwner] = true; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public pure returns(bool) { return true; // Modify to call data contract's status } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function voteAirline(address airline,address voter) internal { require(voter!=airline, "Voter cannot be the same as airline"); if(airlineVotes[airline] == 0){ airlineVotes[airline] = 1; } else { uint temp = airlineVotes[airline]; airlineVotes[airline] = temp+1; } } function airlineRegisteration(address airline) external payable returns(bool success, uint256 votes) { // uint amount;bool isRegistered;bool hasDeposited; // (isRegistered, hasDeposited, amount ) = flightSuretyData.getAirline(airline); // if( msg.value == 0) { // flightSuretyData.setAirline(airline,false,false,0); // return (false , 0); // } // else{ // // address(flightSuretyData).delegatecall(bytes32(keccak256("fund(uint256)"))); // // flightSuretyData.payAirlineRegistrationFee(airline); // emit RegisteringAirline("Register airline "); // return flightSuretyData.registerAirline(airline); // } uint amount;bool isRegistered;bool hasDeposited; (isRegistered, hasDeposited, amount ) = flightSuretyData.getAirline(msg.sender); uint NN = flightSuretyData.getN(); require(hasDeposited, "This airline has not deposited 10 ether"); require(isRegistered,"This sender is not a registered airline"); emit Log(SafeMath.div(NN,2),NN,M,airline, isRegistered); emit RegisteringAirline("Registering Airline"); if( NN<5 ){ require(!registeredAirline[airline], "The airline is already registered "); registeredAirline[airline] = true; flightSuretyData.registerAirline(airline); (isRegistered, hasDeposited, amount ) = flightSuretyData.getAirline(airline); emit AirlineRegistered("Airline is registered"); return (true,M); } else { emit AirlineRegistered("Airline registeration is in consensus "); voteAirline(airline,msg.sender); M = airlineVotes[airline]; if( M >= SafeMath.div(NN,2)){ emit AirlineRegistered("Airline is in consensus Achieved"); emit Log(SafeMath.div(NN,2),NN,M,airline, isRegistered); registeredAirline[airline] = true; flightSuretyData.registerAirline(airline); airlineVotes[airline] = 0; emit AirlineRegistered("Airline registered"); return (true,M); } return(false,M); } return (false,M); } function removeAirline(address airline) external { flightSuretyData.deRegisterAirline(airline); registeredAirline[airline] = false; } function debuging() external returns (uint N, uint m) { uint NN = flightSuretyData.getN(); return (NN,M); } function fundAirline(address airline) public payable requireIsOperational { require(msg.value >= AIRLINE_REGISTRATION_FEE, "Not enough ether to pay"); uint256 returnAmount = msg.value - AIRLINE_REGISTRATION_FEE; flightSuretyData.fund.value(AIRLINE_REGISTRATION_FEE)(airline); msg.sender.transfer(returnAmount); emit AirlineFunded("Airline Funded"); uint amount;bool isRegistered;bool hasDeposited; (isRegistered, hasDeposited, amount ) = flightSuretyData.getAirline(airline); } /** * @dev Register a future flight for insuring. * */ function registerFlight(address airline,string calldata flight , uint256 timestamp) external { // bytes32 key = getFlightKey(airline,flight,timestamp); if(registeredAirline[airline] == true){ flightSuretyData.registerFlight(airline,flight,timestamp,true); } else { flightSuretyData.registerFlight(airline,flight,timestamp,true); } } function buyInsurance(address airline, string calldata flight, uint256 timestamp) external payable { uint amount;bool isRegistered;bool hasDeposited; (isRegistered, hasDeposited, amount ) = flightSuretyData.getAirline(airline); require(isRegistered && hasDeposited ,"Airline is not registered so you cannot buy insurance"); bytes32 key = getFlightKey(airline,flight,timestamp); if(msg.value > 1 ether){ // Extra ethers to be transfered back to the sender msg.sender.transfer(msg.value - MAX_INSURANCE_FEE); flightSuretyData.buy.value(MAX_INSURANCE_FEE)(key,msg.sender); } else { flightSuretyData.buy.value(msg.value)(key,msg.sender); } emit InsuranceStatus("Insurance Bought ",msg.value); } function withdraw() external { emit Log( 22,22,0,msg.sender, true ); uint256 fund = flightSuretyData.getFunds(msg.sender); emit Log( 33,33,fund,msg.sender, true ); msg.sender.transfer(fund); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus ( address airline, string memory flight, uint256 timestamp, uint8 statusCode ) internal { bytes32 key = getFlightKey(airline,flight,timestamp); // require(flightSuretyData.flights[key].airline == airline,"No such flight exist"); // flightSuretyData.flights[key].statusCode = statusCode; // flightSuretyData.flights[key].updatedTimestamp = timestamp; if(statusCode == STATUS_CODE_LATE_AIRLINE) { flightSuretyData.creditInsurees(key); emit InsuranceStatus("Amount Credited to clients account ",0); } } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string calldata flight, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; uint256 public constant MAX_INSURANCE_FEE = 1 ether; uint256 public constant AIRLINE_REGISTRATION_FEE = 10 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Register an oracle with the contract function registerOracle ( ) external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes ( ) view external returns( uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, address airline, string calldata flight, uint256 timestamp, uint8 statusCode ) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns( uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // endregion function getAirline(address airline) public view returns ( bool isRegistered, bool hasDeposited, uint amount ){ return flightSuretyData.getAirline(airline); } } contract FlightSuretyData{ function registerAirline(address airline) external ; function getAirline(address airline) public view returns ( bool isRegistered, bool hasDeposited, uint amount ); function setAirline(address airline, bool isRegistered) public; // function payAirlineRegistrationFee(address airline) external payable; function isOperational() public view returns(bool); function fund(address airline) public payable; function deRegisterAirline(address airline ) external; function creditInsurees(bytes32 flightkey) external; function registerFlight(address airline,string calldata flight,uint256 timestamp,bool isRegistered) external; function buy(bytes32 flightKey,address clientAdd) external payable; function getFunds(address insuree) external returns(uint256 amount); function getN() external returns (uint N); }
Extra ethers to be transfered back to the sender
function buyInsurance(address airline, string calldata flight, uint256 timestamp) external payable { uint amount;bool isRegistered;bool hasDeposited; (isRegistered, hasDeposited, amount ) = flightSuretyData.getAirline(airline); require(isRegistered && hasDeposited ,"Airline is not registered so you cannot buy insurance"); bytes32 key = getFlightKey(airline,flight,timestamp); if(msg.value > 1 ether){ msg.sender.transfer(msg.value - MAX_INSURANCE_FEE); flightSuretyData.buy.value(MAX_INSURANCE_FEE)(key,msg.sender); flightSuretyData.buy.value(msg.value)(key,msg.sender); } emit InsuranceStatus("Insurance Bought ",msg.value); }
1,764,947
[ 1, 7800, 13750, 414, 358, 506, 7412, 329, 1473, 358, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30143, 5048, 295, 1359, 12, 2867, 23350, 1369, 16, 533, 745, 892, 25187, 16, 2254, 5034, 2858, 13, 3903, 8843, 429, 288, 203, 3639, 2254, 3844, 31, 6430, 353, 10868, 31, 6430, 711, 758, 1724, 329, 31, 203, 3639, 261, 291, 10868, 16, 711, 758, 1724, 329, 16, 3844, 262, 273, 25187, 55, 594, 4098, 751, 18, 588, 29752, 1369, 12, 1826, 1369, 1769, 203, 1377, 203, 3639, 2583, 12, 291, 10868, 597, 711, 758, 1724, 329, 269, 6, 29752, 1369, 353, 486, 4104, 1427, 1846, 2780, 30143, 2763, 295, 1359, 8863, 203, 3639, 1731, 1578, 498, 273, 336, 24243, 653, 12, 1826, 1369, 16, 19131, 16, 5508, 1769, 203, 3639, 309, 12, 3576, 18, 1132, 405, 404, 225, 2437, 15329, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 3576, 18, 1132, 300, 4552, 67, 706, 26397, 4722, 67, 8090, 41, 1769, 2398, 203, 5411, 25187, 55, 594, 4098, 751, 18, 70, 9835, 18, 1132, 12, 6694, 67, 706, 26397, 4722, 67, 8090, 41, 21433, 856, 16, 3576, 18, 15330, 1769, 203, 2398, 203, 2398, 25187, 55, 594, 4098, 751, 18, 70, 9835, 18, 1132, 12, 3576, 18, 1132, 21433, 856, 16, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 3639, 3626, 657, 10050, 1359, 1482, 2932, 5048, 295, 1359, 17980, 9540, 3104, 3576, 18, 1132, 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 ]
./full_match/4/0x546097F5045A4f0d8675fA6edE2FC15D5147A046/sources/contracts/7_Minigame.sol
uint predictedAmount;
struct Player { int id; string predicted; address account; } event emitPredictedSuccess(Player player);
652,257
[ 1, 11890, 15071, 6275, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 19185, 288, 203, 3639, 509, 612, 31, 203, 3639, 533, 15071, 31, 203, 3639, 1758, 2236, 31, 203, 565, 289, 203, 203, 565, 871, 3626, 21362, 329, 4510, 12, 12148, 7291, 1769, 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 ]
./partial_match/42/0xFFC46daFE045E1239E64cbc0e324F3d2feb5dF15/sources/Ris3Governance.sol
get tax pool address
function getTaxPoolAddress() public view returns (address _taxPoolAddressAddress) { return address(taxes); }
3,417,279
[ 1, 588, 5320, 2845, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22136, 2864, 1887, 1435, 1071, 1476, 1135, 261, 2867, 389, 8066, 2864, 1887, 1887, 13, 288, 203, 3639, 327, 1758, 12, 8066, 281, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.10; /* ---------------------------------------------------------------------------------------- Dev: "Owned" to ensure control of contracts Identical to https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol ---------------------------------------------------------------------------------------- */ contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } /* ---------------------------------------------------------------------------------------- Dev: SafeMath library Identical to https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol ---------------------------------------------------------------------------------------- */ library SafeMath { function safeMul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(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 safeSub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); // Ensuring no negatives return a - b; } function safeAdd(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a && c>=b); return c; } } /* ---------------------------------------------------------------------------------------- Dev: ESG Asset Holder is called when the token "burn" function is called Sum: Locked to false so users cannot burn their tokens until the Asset Contract is put in place with value. ---------------------------------------------------------------------------------------- */ contract ESGAssetHolder { function burn(address _holder, uint _amount) returns (bool result) { _holder = 0x0; // To avoid variable not used issue on deployment _amount = 0; // To avoid variable not used issue on deployment return false; } } /* ---------------------------------------------------------------------------------------- Dev: The Esports Gold Token: ERC20 standard token with MINT and BURN functions Func: Mint, Approve, Transfer, TransferFrom Note: Mint function takes UNITS of tokens to mint as ICO event is set to have a minimum contribution of 1 token. All other functions (transfer etc), the value to transfer is the FULL DECIMAL value The user is only ever presented with the latter option, therefore should avoid any confusion. ---------------------------------------------------------------------------------------- */ contract ESGToken is Owned { string public name = "ESG Token"; // Name of token string public symbol = "ESG"; // Token symbol uint256 public decimals = 3; // Decimals for the token uint256 public currentSupply; // Current supply of tokens uint256 public supplyCap; // Hard cap on supply of tokens address public ICOcontroller; // Controlling contract from ICO address public timelockTokens; // Address for locked management tokens bool public tokenParametersSet; // Ensure that parameters required are set bool public controllerSet; // Ensure that ICO controller is set mapping (address => uint256) public balanceOf; // Balances of addresses mapping (address => mapping (address => uint)) public allowance; // Allowances from addresses mapping (address => bool) public frozenAccount; // Safety mechanism modifier onlyControllerOrOwner() { // Ensures that only contracts can manage key functions require(msg.sender == ICOcontroller || msg.sender == owner); _; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Mint(address owner, uint amount); event FrozenFunds(address target, bool frozen); event Burn(address coinholder, uint amount); /* ---------------------------------------------------------------------------------------- Dev: Constructor param: Owner: Address of owner Name: Esports Gold Token Sym: ESG_TKN Dec: 3 Cap: Hard coded cap to ensure excess tokens cannot be minted Other parameters have been set up as a separate function to help lower initial gas deployment cost. ---------------------------------------------------------------------------------------- */ function ESGToken() { currentSupply = 0; // Starting supply is zero supplyCap = 0; // Hard cap supply in Tokens set by ICO tokenParametersSet = false; // Ensure parameters are set controllerSet = false; // Ensure controller is set } /* ---------------------------------------------------------------------------------------- Dev: Key parameters to setup for ICO event Param: _ico Address of the ICO Event contract to ensure the ICO event can control the minting function ---------------------------------------------------------------------------------------- */ function setICOController(address _ico) onlyOwner { // ICO event address is locked in require(_ico != 0x0); ICOcontroller = _ico; controllerSet = true; } /* ---------------------------------------------------------------------------------------- NEW Dev: Address for the timelock tokens to be held Param: _timelockAddr Address of the timelock contract that will hold the locked tokens ---------------------------------------------------------------------------------------- */ function setParameters(address _timelockAddr) onlyOwner { require(_timelockAddr != 0x0); timelockTokens = _timelockAddr; tokenParametersSet = true; } function parametersAreSet() constant returns (bool) { return tokenParametersSet && controllerSet; } /* ---------------------------------------------------------------------------------------- Dev: Set the total number of Tokens that can be minted Param: _supplyCap The number of tokens (in whole units) that can be minted. This number then gets increased by the decimal number ---------------------------------------------------------------------------------------- */ function setTokenCapInUnits(uint256 _supplyCap) onlyControllerOrOwner { // Supply cap in UNITS assert(_supplyCap > 0); supplyCap = SafeMath.safeMul(_supplyCap, (10**decimals)); } /* ---------------------------------------------------------------------------------------- Dev: Mint the number of tokens for the timelock contract Param: _mMentTkns Number of tokens in whole units that need to be locked into the Timelock ---------------------------------------------------------------------------------------- */ function mintLockedTokens(uint256 _mMentTkns) onlyControllerOrOwner { assert(_mMentTkns > 0); assert(tokenParametersSet); mint(timelockTokens, _mMentTkns); } /* ---------------------------------------------------------------------------------------- Dev: Gets the balance of the address owner Param: _owner Address of the owner querying their balance ---------------------------------------------------------------------------------------- */ function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } /* ---------------------------------------------------------------------------------------- Dev: Mint ESG Tokens by controller Control: OnlyControllers. ICO event needs to be able to control the minting function Param: Address Address for tokens to be minted to Amount Number of tokens to be minted (in whole UNITS. Min minting is 1 token) Minimum ETH contribution in ICO event is 0.01ETH at 100 tokens per ETH ---------------------------------------------------------------------------------------- */ function mint(address _address, uint _amount) onlyControllerOrOwner { require(_address != 0x0); uint256 amount = SafeMath.safeMul(_amount, (10**decimals)); // Tokens minted using unit parameter supplied // Ensure that supplyCap is set and that new tokens don't breach cap assert(supplyCap > 0 && amount > 0 && SafeMath.safeAdd(currentSupply, amount) <= supplyCap); balanceOf[_address] = SafeMath.safeAdd(balanceOf[_address], amount); // Add tokens to address currentSupply = SafeMath.safeAdd(currentSupply, amount); // Add to supply Mint(_address, amount); } /* ---------------------------------------------------------------------------------------- Dev: ERC20 standard transfer function Param: _to Address to send to _value Number of tokens to be sent - in FULL decimal length Ref: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/BasicToken.sol ---------------------------------------------------------------------------------------- */ function transfer(address _to, uint _value) returns (bool success) { require(!frozenAccount[msg.sender]); // Ensure account is not frozen /* Update balances from "from" and "to" addresses with the tokens transferred safeSub method ensures that address sender has enough tokens to send */ balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } /* ---------------------------------------------------------------------------------------- Dev: ERC20 standard transferFrom function Param: _from Address to send from _to Address to send to Amount Number of tokens to be sent - in FULL decimal length ---------------------------------------------------------------------------------------- */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); // Check account is not frozen /* Ensure sender has been authorised to send the required number of tokens */ if (allowance[_from][msg.sender] < _value) return false; /* Update allowance of sender to reflect tokens sent */ allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); /* Update balances from "from" and "to" addresses with the tokens transferred safeSub method ensures that address sender has enough tokens to send */ balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } /* ---------------------------------------------------------------------------------------- Dev: ERC20 standard approve function Param: _spender Address of sender who is approved _value The number of tokens (full decimals) that are approved ---------------------------------------------------------------------------------------- */ function approve(address _spender, uint256 _value) // FULL DECIMALS OF TOKENS returns (bool success) { require(!frozenAccount[msg.sender]); // Check account is not frozen /* Requiring the user to set to zero before resetting to nonzero */ if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) { return false; } allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* ---------------------------------------------------------------------------------------- Dev: Function to check the amount of tokens that the owner has allowed the "spender" to transfer Param: _owner Address of the authoriser who owns the tokens _spender Address of sender who will be authorised to spend the tokens ---------------------------------------------------------------------------------------- */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowance[_owner][_spender]; } /* ---------------------------------------------------------------------------------------- Dev: As ESG is aiming to be a regulated betting operator. Regulatory hurdles may require this function if an account on the betting platform, using the token, breaches a regulatory requirement. ESG can then engage with the account holder to get it unlocked This does not stop the token accruing value from its share of the Asset Contract Param: _target Address of account _freeze Boolean to lock/unlock account Ref: This is a replica of the code as per https://ethereum.org/token ---------------------------------------------------------------------------------------- */ function freezeAccount(address target, bool freeze) onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /* ---------------------------------------------------------------------------------------- Dev: Burn function: User is able to burn their token for a share of the ESG Asset Contract Note: Deployed with the ESG Asset Contract set to false to ensure token holders cannot accidentally burn their tokens for zero value Param: _amount Number of tokens (full decimals) that should be burnt Ref: Based on the open source TokenCard Burn function. A copy can be found at https://github.com/bokkypoobah/TokenCardICOAnalysis ---------------------------------------------------------------------------------------- */ function burn(uint _amount) returns (bool result) { if (_amount > balanceOf[msg.sender]) return false; // If owner has enough to burn /* Remove tokens from circulation Update sender's balance of tokens */ balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _amount); currentSupply = SafeMath.safeSub(currentSupply, _amount); // Call burn function result = esgAssetHolder.burn(msg.sender, _amount); require(result); Burn(msg.sender, _amount); } /* ---------------------------------------------------------------------------------------- Dev: Section of the contract that links to the ESG Asset Contract Note: Deployed with the ESG Asset Contract set to false to ensure token holders cannot accidentally burn their tokens for zero value Param: _amount Number of tokens (full decimals) that should be burnt Ref: Based on the open source TokenCard Burn function. A copy can be found at https://github.com/bokkypoobah/TokenCardICOAnalysis ---------------------------------------------------------------------------------------- */ ESGAssetHolder esgAssetHolder; // Holds the accumulated asset contract bool lockedAssetHolder; // Will be locked to stop tokenholder to be upgraded function lockAssetHolder() onlyOwner { // Locked once deployed lockedAssetHolder = true; } function setAssetHolder(address _assetAdress) onlyOwner { // Used to lock in the Asset Contract assert(!lockedAssetHolder); // Check that we haven't locked the asset holder yet esgAssetHolder = ESGAssetHolder(_assetAdress); } }
Balances of addresses
mapping (address => uint256) public balanceOf;
12,571,900
[ 1, 38, 26488, 434, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 15604, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library BorrowingIssuanceProperty { //struct definition struct Data { address borrowingTokenAddress; address collateralTokenAddress; uint256 borrowingAmount; uint256 collateralRatio; uint256 collateralAmount; uint256 interestRate; uint256 interestAmount; uint256 tenorDays; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_borrowingTokenAddress(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_collateralTokenAddress(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_borrowingAmount(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_collateralRatio(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_collateralAmount(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_interestRate(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_interestAmount(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_tenorDays(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.borrowingTokenAddress = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.collateralTokenAddress = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.borrowingAmount = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralRatio( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.collateralRatio = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.collateralAmount = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestRate( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.interestRate = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.interestAmount = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_tenorDays( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.tenorDays = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.borrowingTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.collateralTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.borrowingAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralRatio, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.interestRate, pointer, bs); pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.interestAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.tenorDays, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @return The number of bytes encoded in estimation */ function _estimate( Data memory /* r */ ) internal pure returns (uint) { uint256 e; e += 1 + 23; e += 1 + 23; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.borrowingTokenAddress = input.borrowingTokenAddress; output.collateralTokenAddress = input.collateralTokenAddress; output.borrowingAmount = input.borrowingAmount; output.collateralRatio = input.collateralRatio; output.collateralAmount = input.collateralAmount; output.interestRate = input.interestRate; output.interestAmount = input.interestAmount; output.tenorDays = input.tenorDays; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingIssuanceProperty library BorrowingEngagementProperty { //enum definition // Solidity enum definitions enum LoanState { LoanStateUnknown, Unpaid, Repaid, Delinquent } // Solidity enum encoder function encode_LoanState(LoanState x) internal pure returns (int64) { if (x == LoanState.LoanStateUnknown) { return 0; } if (x == LoanState.Unpaid) { return 1; } if (x == LoanState.Repaid) { return 2; } if (x == LoanState.Delinquent) { return 3; } revert(); } // Solidity enum decoder function decode_LoanState(int64 x) internal pure returns (LoanState) { if (x == 0) { return LoanState.LoanStateUnknown; } if (x == 1) { return LoanState.Unpaid; } if (x == 2) { return LoanState.Repaid; } if (x == 3) { return LoanState.Delinquent; } revert(); } //struct definition struct Data { BorrowingEngagementProperty.LoanState loanState; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_loanState(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_loanState( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); BorrowingEngagementProperty.LoanState x = decode_LoanState(tmp); if (isNil(r)) { counters[1] += 1; } else { r.loanState = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int64 _enum_loanState = encode_LoanState(r.loanState); pointer += ProtoBufRuntime._encode_enum(_enum_loanState, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(encode_LoanState(r.loanState)); return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.loanState = input.loanState; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingEngagementProperty
* @dev The decoder for reading a field @param p The offset of bytes array to start decode @param bs The bytes array to be decoded @param r The in-memory struct @param counters The counters for repeated fields @return The number of bytes decoded/* if `r` is NULL, then only counting the number of fields./
function _read_tenorDays( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[8] += 1; r.tenorDays = x; if (counters[8] > 0) counters[8] -= 1; } return sz; }
6,490,026
[ 1, 1986, 8320, 364, 6453, 279, 652, 225, 293, 1021, 1384, 434, 1731, 526, 358, 787, 2495, 225, 7081, 1021, 1731, 526, 358, 506, 6383, 225, 436, 1021, 316, 17, 7858, 1958, 225, 13199, 1021, 13199, 364, 12533, 1466, 327, 1021, 1300, 434, 1731, 6383, 19, 309, 1375, 86, 68, 353, 3206, 16, 1508, 1338, 22075, 326, 1300, 434, 1466, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 389, 896, 67, 2253, 280, 9384, 12, 203, 565, 2254, 5034, 293, 16, 203, 565, 1731, 3778, 7081, 16, 203, 565, 1910, 3778, 436, 16, 203, 565, 2254, 63, 29, 65, 3778, 13199, 203, 225, 262, 2713, 16618, 1135, 261, 11890, 13, 288, 203, 565, 261, 11890, 5034, 619, 16, 2254, 5034, 11262, 13, 273, 7440, 5503, 5576, 6315, 3922, 67, 18281, 67, 11890, 5034, 12, 84, 16, 7081, 1769, 203, 565, 309, 261, 291, 12616, 12, 86, 3719, 288, 203, 1377, 13199, 63, 28, 65, 1011, 404, 31, 203, 1377, 436, 18, 2253, 280, 9384, 273, 619, 31, 203, 1377, 309, 261, 23426, 63, 28, 65, 405, 374, 13, 13199, 63, 28, 65, 3947, 404, 31, 203, 565, 289, 203, 565, 327, 11262, 31, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./owner/Operator.sol"; import "./utils/ContractGuard.sol"; import "./interfaces/IEpoch.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IChipSwap.sol"; import "./interfaces/IBoardroom.sol"; import "./interfaces/IBasisAsset.sol"; import "./interfaces/IFishRewardPool.sol"; contract Treasury is ContractGuard, ITreasury, Operator { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // State variables. bool public migrated = false; bool public initialized = false; bool public inDebtPhase = false; // Epoch. struct epochHistory { uint256 bonded; uint256 redeemed; uint256 expandedAmount; uint256 epochPrice; uint256 endEpochPrice; } epochHistory[] public history; uint256 public startTime; uint256 public lastEpochTime; uint256 private _epoch = 0; uint256 public epochSupplyContractionLeft = 0; // Core components. address public CHIP; address public FISH; address public MPEA; address public boardroom; address public boardroomSecond; address public CHIPOracle; address public ETH = address(0xEb8250680Fd67c0C9FE2C015AC702C8EdF02F335); // need to change address public CHIP_ETH = address(0xaB5a4bFe8E7a5A2628cC690519bcC3481D66e9e0); address public FISH_ETH = address(0x3715340BC619E5aDbca158Ab459F2EfFDa545675); IChipSwap public ChipSwapMechanism; IFishRewardPool public fishPool; // Price. uint256 public CHIPPriceOne; uint256 public CHIPPriceCeiling; uint256 public seigniorageSaved; uint256 public maxSupplyExpansionPercent; uint256 public maxSupplyExpansionPercentInDebtPhase; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDeptRatioPercent; uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; uint256 public previousEpochDollarPrice; uint256 public allocateSeigniorageSalary; uint256 public maxDiscountRate; // When purchasing MPEA. uint256 public maxPremiumRate; // When redeeming MPEA. uint256 public discountPercent; uint256 public premiumPercent; uint256 public mintingFactorForPayingDebt; // Print extra CHIP during dept phase. address public daoFund; uint256 public daoFundSharedPercent; address public secondBoardRoomFund; uint256 public secondBoardRoomFundSharedPercent; address public marketingFund; uint256 public marketingFundSharedPercent; // Events. event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event RedeemedBonds(address indexed from, uint256 CHIPAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 CHIPAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event SecondBoardRoomFundFunded(uint256 timestamp, uint256 seigniorage); event MarketingFundFunded(uint256 timestamp, uint256 seigniorage); event BoardroomSecondSet(address _boardroom2); modifier checkCondition { require(!migrated, "Treasury: Migrated."); require(block.timestamp >= startTime, "Treasury: Not started yet."); _; } modifier checkEpoch { uint256 _nextEpochPoint = nextEpochPoint(); require(block.timestamp >= _nextEpochPoint, "Treasury: Not opened yet."); _; lastEpochTime = _nextEpochPoint; _epoch = _epoch.add(1); epochSupplyContractionLeft = (getEthPrice() > CHIPPriceCeiling) ? 0 : IERC20(CHIP).totalSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator { require(IBasisAsset(CHIP).operator() == address(this) && IBasisAsset(FISH).operator() == address(this) && IBasisAsset(MPEA).operator() == address(this) && Operator(boardroom).operator() == address(this), "Treasury: Bad permissions."); _; } modifier notInitialized { require(!initialized, "Treasury: Already initialized."); _; } // Epoch. function epoch() external view override returns (uint256) { return _epoch; } function nextEpochPoint() public view override returns (uint256) { return lastEpochTime.add(nextEpochLength()); } function nextEpochLength() public view override returns (uint256 _length) { if (_epoch <= bootstrapEpochs) { // 3 first epochs with 6h long. _length = 15 minutes; } else { uint256 CHIPPrice = getEthPrice(); _length = (CHIPPrice > CHIPPriceCeiling) ? 15 minutes : 10 minutes; } } // Oracle. function getEthPrice() public view override returns (uint256 CHIPPrice) { try IOracle(CHIPOracle).twap(CHIP, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: Failed to consult CHIP price from the oracle."); } } // Budget. function getReserve() external view returns (uint256) { return seigniorageSaved; } function getBurnableDollarLeft() external view returns (uint256 _burnableDollarLeft) { uint256 _CHIPPrice = getEthPrice(); if (_CHIPPrice <= CHIPPriceOne) { uint256 _CHIPSupply = IERC20(CHIP).totalSupply(); uint256 _bondMaxSupply = _CHIPSupply.mul(maxDeptRatioPercent).div(10000); uint256 _bondSupply = IERC20(MPEA).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnableDollar = _maxMintableBond.mul(_CHIPPrice).div(1e18); _burnableDollarLeft = Math.min(epochSupplyContractionLeft, _maxBurnableDollar); } } } function getRedeemableBonds() external view returns (uint256 _redeemableBonds) { uint256 _CHIPPrice = getEthPrice(); if (_CHIPPrice > CHIPPriceCeiling) { uint256 _totalDollar = IERC20(CHIP).balanceOf(address(this)); uint256 _rate = getBondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalDollar.mul(1e18).div(_rate); } } } function getBondDiscountRate() public view returns (uint256 _rate) { uint256 _CHIPPrice = getEthPrice(); if (_CHIPPrice <= CHIPPriceOne) { if (discountPercent == 0) { // No discount. _rate = CHIPPriceOne; } else { uint256 _bondAmount = CHIPPriceOne.mul(1e18).div(_CHIPPrice); // To burn 1 CHIP. uint256 _discountAmount = _bondAmount.sub(CHIPPriceOne).mul(discountPercent).div(10000); _rate = CHIPPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function getBondPremiumRate() public view returns (uint256 _rate) { uint256 _CHIPPrice = getEthPrice(); if (_CHIPPrice > CHIPPriceCeiling) { if (premiumPercent == 0) { // No premium bonus. _rate = CHIPPriceOne; } else { uint256 _premiumAmount = _CHIPPrice.sub(CHIPPriceOne).mul(premiumPercent).div(10000); _rate = CHIPPriceOne.add(_premiumAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } // Governance. function initialize( address _CHIP, address _MPEA, address _FISH, uint256 _startTime ) external onlyOperator notInitialized { history.push(epochHistory({bonded: 0, redeemed: 0, expandedAmount: 0, epochPrice: 0, endEpochPrice: 0})); CHIP = _CHIP; MPEA = _MPEA; FISH = _FISH; startTime = _startTime; lastEpochTime = _startTime.sub(15 minutes); CHIPPriceOne = 10**18; CHIPPriceCeiling = CHIPPriceOne.mul(10001).div(10000); maxSupplyExpansionPercent = 300; // Up to 3.0% supply for expansion. maxSupplyExpansionPercentInDebtPhase = 300; // Up to 3% supply for expansion in debt phase (to pay debt faster). bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor. seigniorageExpansionFloorPercent = 5000; // At least 50% of expansion reserved for boardroom. maxSupplyContractionPercent = 350; // Up to 3.5% supply for contraction (to burn CHIP and mint MPEA). maxDeptRatioPercent = 5000; // Up to 50% supply of MEB to purchase. bootstrapEpochs = 3; // First 3 epochs with expansion. bootstrapSupplyExpansionPercent = 300; seigniorageSaved = IERC20(CHIP).balanceOf(address(this)); // Set seigniorageSaved to its balance. allocateSeigniorageSalary = 0.001 ether; // 0.001 CHIP salary for calling allocateSeigniorage. maxDiscountRate = 13e17; // 30% - when purchasing bond. maxPremiumRate = 13e17; // 30% - when redeeming bond. discountPercent = 0; // No discount. premiumPercent = 6500; // 65% premium. mintingFactorForPayingDebt = 10000; // 100% daoFundSharedPercent = 3500; // 35% toward DAO Fund. secondBoardRoomFundSharedPercent = 0; marketingFundSharedPercent = 0; initialized = true; emit Initialized(msg.sender, block.number); } function resetStartTime(uint256 _startTime) external onlyOperator { require(_epoch == 0, "already started"); startTime = _startTime; lastEpochTime = _startTime.sub(15 minutes); } function setBoardroomSecond(address _boardroom2) external onlyOperator { boardroomSecond = _boardroom2; emit BoardroomSecondSet(_boardroom2); } function setDollarPriceCeiling(uint256 _CHIPPriceCeiling) external onlyOperator { require(_CHIPPriceCeiling >= CHIPPriceOne && _CHIPPriceCeiling <= CHIPPriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2] CHIPPriceCeiling = _CHIPPriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent, uint256 _maxSupplyExpansionPercentInDebtPhase) external onlyOperator { require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%] require(_maxSupplyExpansionPercentInDebtPhase >= 10 && _maxSupplyExpansionPercentInDebtPhase <= 1500, "_maxSupplyExpansionPercentInDebtPhase: out of range"); // [0.1%, 15%] require(_maxSupplyExpansionPercent <= _maxSupplyExpansionPercentInDebtPhase, "_maxSupplyExpansionPercent is over _maxSupplyExpansionPercentInDebtPhase"); maxSupplyExpansionPercent = _maxSupplyExpansionPercent; maxSupplyExpansionPercentInDebtPhase = _maxSupplyExpansionPercentInDebtPhase; } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDeptRatioPercent(uint256 _maxDeptRatioPercent) external onlyOperator { require(_maxDeptRatioPercent >= 1000 && _maxDeptRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDeptRatioPercent = _maxDeptRatioPercent; } function setBootstrapParams(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { require(_bootstrapEpochs <= 90, "_bootstrapSupplyExpansionPercent: out of range"); // <= 1 month require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%] bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _secondBoardRoomFund, uint256 _secondBoardRoomFundSharedPercent, address _marketingFund, uint256 _marketingFundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_daoFundSharedPercent <= 3500, "out of range"); // <= 35% require(_secondBoardRoomFund != address(0), "zero"); require(_secondBoardRoomFundSharedPercent <= 1000, "out of range"); // <= 10% require(_marketingFund != address(0), "zero"); require(_marketingFundSharedPercent <= 1000, "out of range"); // <= 10% daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; secondBoardRoomFund = _secondBoardRoomFund; secondBoardRoomFundSharedPercent = _secondBoardRoomFundSharedPercent; marketingFund = _marketingFund; marketingFundSharedPercent = _marketingFundSharedPercent; } function setAllocateSeigniorageSalary(uint256 _allocateSeigniorageSalary) external onlyOperator { require(_allocateSeigniorageSalary <= 100 ether, "Treasury: dont pay too much"); allocateSeigniorageSalary = _allocateSeigniorageSalary; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%] mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } function migrate(address target) external onlyOperator checkOperator { require(!migrated, "Treasury: migrated"); // CHIP Operator(CHIP).transferOperator(target); Operator(CHIP).transferOwnership(target); IERC20(CHIP).transfer(target, IERC20(CHIP).balanceOf(address(this))); // MPEA Operator(MPEA).transferOperator(target); Operator(MPEA).transferOwnership(target); IERC20(MPEA).transfer(target, IERC20(MPEA).balanceOf(address(this))); // FISH Operator(FISH).transferOperator(target); Operator(FISH).transferOwnership(target); IERC20(FISH).transfer(target, IERC20(FISH).balanceOf(address(this))); migrated = true; emit Migration(target); } // Mutators. function _updateEthPrice() internal { try IOracle(CHIPOracle).update() {} catch {} } function buyBonds(uint256 _CHIPAmount, uint256 targetPrice) external override onlyOneBlock checkCondition checkOperator { require(_epoch >= bootstrapEpochs, "Treasury: still in boostrap"); require(_CHIPAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 CHIPPrice = history[_epoch].epochPrice; require( CHIPPrice < CHIPPriceCeiling, // price < 1 ETH. "Treasury: CHIP Price not eligible for bond purchase." ); require(_CHIPAmount <= epochSupplyContractionLeft, "Treasury: Not enough bond left to purchase."); uint256 _rate = getBondDiscountRate(); require(_rate > 0, "Treasury: Invalid bond rate."); uint256 _bondAmount = _CHIPAmount.mul(_rate).div(1e18); uint256 CHIPSupply = IERC20(CHIP).totalSupply(); uint256 newBondSupply = IERC20(MPEA).totalSupply().add(_bondAmount); require(newBondSupply <= CHIPSupply.mul(maxDeptRatioPercent).div(10000), "Over max debt ratio."); IBasisAsset(CHIP).burnFrom(msg.sender, _CHIPAmount); IBasisAsset(MPEA).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_CHIPAmount); _updateEthPrice(); history[_epoch].bonded = history[_epoch].bonded.add(_bondAmount); emit BoughtBonds(msg.sender, _CHIPAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external override onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: Cannot redeem bonds with zero amount."); uint256 CHIPPrice = history[_epoch].epochPrice; require( CHIPPrice > CHIPPriceCeiling, // price > $1.01. "Treasury: CHIP Price not eligible for bond purchase." ); uint256 _rate = getBondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _CHIPAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(CHIP).balanceOf(address(this)) >= _CHIPAmount, "Treasury: Treasury has no more budget."); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _CHIPAmount)); IBasisAsset(MPEA).burnFrom(msg.sender, _bondAmount); IERC20(CHIP).safeTransfer(msg.sender, _CHIPAmount); history[_epoch].redeemed = history[_epoch].redeemed.add(_CHIPAmount); _updateEthPrice(); emit RedeemedBonds(msg.sender, _CHIPAmount, _bondAmount); } function _sendToBoardRoom(uint256 _amount) internal { IBasisAsset(CHIP).mint(address(this), _amount); if (daoFundSharedPercent > 0) { uint256 _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(CHIP).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(block.timestamp, _daoFundSharedAmount); _amount = _amount.sub(_daoFundSharedAmount); } if (marketingFundSharedPercent > 0) { uint256 _marketingSharedAmount = _amount.mul(marketingFundSharedPercent).div(10000); IERC20(CHIP).transfer(marketingFund, _marketingSharedAmount); emit MarketingFundFunded(block.timestamp, _marketingSharedAmount); _amount = _amount.sub(_marketingSharedAmount); } if (boardroomSecond != address(0) && secondBoardRoomFundSharedPercent > 0) { uint256 _secondBoardRoomFundSharedAmount = _amount.mul(secondBoardRoomFundSharedPercent).div(10000); IERC20(CHIP).safeApprove(boardroom, 0); IERC20(CHIP).safeApprove(boardroom, _secondBoardRoomFundSharedAmount); IBoardroom(boardroomSecond).allocateSeigniorage(_secondBoardRoomFundSharedAmount); _amount = _amount.sub(_secondBoardRoomFundSharedAmount); } IERC20(CHIP).safeApprove(boardroom, 0); IERC20(CHIP).safeApprove(boardroom, _amount); IBoardroom(boardroom).allocateSeigniorage(_amount); emit BoardroomFunded(block.timestamp, _amount); } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { inDebtPhase = false; _updateEthPrice(); previousEpochDollarPrice = getEthPrice(); history.push(epochHistory({bonded: 0, redeemed: 0, expandedAmount: 0, epochPrice: previousEpochDollarPrice, endEpochPrice: 0})); history[_epoch].endEpochPrice = previousEpochDollarPrice; uint256 CHIPSupply = IERC20(CHIP).totalSupply().sub(seigniorageSaved); uint256 ExpansionPercent; if(CHIPSupply < 500 ether) ExpansionPercent = 300; // 3% else if(CHIPSupply >= 500 ether && CHIPSupply < 1000 ether) ExpansionPercent = 200; // 2% else if(CHIPSupply >= 1000 ether && CHIPSupply < 2000 ether) ExpansionPercent = 150; // 1.5% else if(CHIPSupply >= 2000 ether && CHIPSupply < 5000 ether) ExpansionPercent = 125; // 1.25% else if(CHIPSupply >= 5000 ether && CHIPSupply < 10000 ether) ExpansionPercent = 100; // 1% else if(CHIPSupply >= 10000 ether && CHIPSupply < 20000 ether) ExpansionPercent = 75; // 0.75% else if(CHIPSupply >= 20000 ether && CHIPSupply < 50000 ether) ExpansionPercent = 50; // 0.5% else if(CHIPSupply >= 50000 ether && CHIPSupply < 100000 ether) ExpansionPercent = 25; // 0.25% else if(CHIPSupply >= 100000 ether && CHIPSupply < 200000 ether) ExpansionPercent = 15; // 0.15% else ExpansionPercent = 10; // 0.1% maxSupplyExpansionPercent = ExpansionPercent; if (_epoch < bootstrapEpochs) { // 3 first epochs expansion. _sendToBoardRoom(CHIPSupply.mul(ExpansionPercent).div(10000)); ChipSwapMechanism.unlockFish(6); // When expansion phase, 6 hours worth fish will be unlocked. fishPool.set(4, 0); // Disable MPEA/CHIP pool when expansion phase. history[_epoch.add(1)].expandedAmount = CHIPSupply.mul(ExpansionPercent).div(10000); } else { if (previousEpochDollarPrice > CHIPPriceCeiling) { // Expansion ($CHIP Price > 1 ETH): there is some seigniorage to be allocated fishPool.set(4, 0); // Disable MPEA/CHIP pool when expansion phase. ChipSwapMechanism.unlockFish(6); // When expansion phase, 6 hours worth fish will be unlocked. uint256 bondSupply = IERC20(MPEA).totalSupply(); uint256 _percentage = previousEpochDollarPrice.sub(CHIPPriceOne); uint256 _savedForBond; uint256 _savedForBoardRoom; if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // Saved enough to pay dept, mint as usual rate. uint256 _mse = ExpansionPercent.mul(1e14); if (_percentage > _mse) { _percentage = _mse; } _savedForBoardRoom = CHIPSupply.mul(_percentage).div(1e18); history[_epoch.add(1)].expandedAmount = CHIPSupply.mul(_percentage).div(1e18); } else { // Have not saved enough to pay dept, mint more. uint256 _mse = ExpansionPercent.mul(1e14); if (_percentage > _mse) { _percentage = _mse; } uint256 _seigniorage = CHIPSupply.mul(_percentage).div(1e18); history[_epoch.add(1)].expandedAmount = CHIPSupply.mul(_percentage).div(1e18); _savedForBoardRoom = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForBoardRoom); if (mintingFactorForPayingDebt > 0) { inDebtPhase = true; _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForBoardRoom > 0) { _sendToBoardRoom(_savedForBoardRoom); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(CHIP).mint(address(this), _savedForBond); emit TreasuryFunded(block.timestamp, _savedForBond); } } else { // Contraction phase. ChipSwapMechanism.unlockFish(4); // When contraction phase, 4 hours worth fish will be unlocked. fishPool.set(4, 3000); // Enable MPEA/CHIP pool when contraction phase. maxSupplyExpansionPercent = 0; } } if (allocateSeigniorageSalary > 0) { IBasisAsset(CHIP).mint(address(msg.sender), allocateSeigniorageSalary); } } // Boardroom controls. function boardroomSetOperator(address _operator) external onlyOperator { IBoardroom(boardroom).setOperator(_operator); } function boardroomSetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator { IBoardroom(boardroom).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs); } function boardroomAllocateSeigniorage(uint256 amount) external onlyOperator { IBoardroom(boardroom).allocateSeigniorage(amount); } function boardroomGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { IBoardroom(boardroom).governanceRecoverUnsupported(_token, _amount, _to); } // ChipSwap controls. function swapChipToFish(uint256 ChipAmount) external { uint256 FishPricePerChip = getFishAmountPerChip(); uint256 FishAmount = ChipAmount.mul(FishPricePerChip).div(1e18); ChipSwapMechanism.swap(msg.sender, ChipAmount, FishAmount); ERC20Burnable(CHIP).burnFrom(msg.sender, ChipAmount); } function getFishAmountPerChip() public view returns (uint256) { uint256 ChipBalance = IERC20(CHIP).balanceOf(CHIP_ETH); // CHIP/ETH pool. uint256 FishBalance = IERC20(FISH).balanceOf(FISH_ETH); // FISH/ETH pool. uint256 rate1 = uint256(1e18).mul(ChipBalance).div(IERC20(ETH).balanceOf(CHIP_ETH)); uint256 rate2 = uint256(1e18).mul(FishBalance).div(IERC20(ETH).balanceOf(FISH_ETH)); return uint256(1e18).mul(rate2).div(rate1); } function setExtraContract( IFishRewardPool _fishPool, IChipSwap _chipswapMechanism, address _CHIPOracle, address _boardroom ) external onlyOperator { fishPool = _fishPool; ChipSwapMechanism = _chipswapMechanism; CHIPOracle = _CHIPOracle; boardroom = _boardroom; } }
Boardroom controls.
function boardroomSetOperator(address _operator) external onlyOperator { IBoardroom(boardroom).setOperator(_operator); }
7,233,801
[ 1, 22233, 13924, 11022, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11094, 13924, 694, 5592, 12, 2867, 389, 9497, 13, 3903, 1338, 5592, 288, 203, 3639, 467, 22233, 13924, 12, 3752, 13924, 2934, 542, 5592, 24899, 9497, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC721Metadata, IERC721, IERC165} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import {IERC721Receiver} from '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {Context} from '@openzeppelin/contracts/utils/Context.sol'; import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {ERC165} from '@openzeppelin/contracts/utils/introspection/ERC165.sol'; import {AggrOwnable} from './AggrOwnable.sol'; contract AggrBaseNFT is Context, ERC165, IERC721, IERC721Metadata, AggrOwnable { using Address for address; using Strings for uint256; // Token name string override public name; // Token symbol string override public symbol = 'AGGR'; // Token URL string public baseURI; // Mapping from token ID to token creator address mapping (uint256 => address) private _rednecks; // Mapping from token ID to victim address mapping (uint256 => address) private _victims; // Mapping victim address to token count mapping (address => uint256) private _swearWords; // 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; modifier Exists(uint256 tokenId) { require(_rednecks[tokenId] != address(0), 'A: fuck'); _; } constructor(string memory name_) { name = name_; } // OnlyAggrOwner functions function setBaseURI(string memory _baseURI) external OnlyAggrOwner { baseURI = _baseURI; } // Other functions /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address victim) external view override returns (uint256) { require(victim != address(0), 'A: goof not found'); return _swearWords[victim]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) external view override returns (address) { address victim = _victims[tokenId]; require(victim != address(0), 'A: fuck off'); return victim; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) external view Exists(tokenId) override returns (string memory) { string memory _baseURI = baseURI; return bytes(_baseURI).length > 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) external override { address redneck = _rednecks[tokenId]; require(to != redneck, 'A: what the fuck?'); require(_msgSender() == redneck || isApprovedForAll(redneck, _msgSender()), 'A: you shall not pass (A)' ); _approve(redneck, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) external view Exists(tokenId) override returns (address) { return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address looser, bool approved) external override { address bossOfThisGum = _msgSender(); require(looser != bossOfThisGum, 'A: idiot'); _operatorApprovals[bossOfThisGum][looser] = approved; emit ApprovalForAll(bossOfThisGum, looser, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address bossOfThisGum, address looser) public view override returns (bool) { return _operatorApprovals[bossOfThisGum][looser]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) external override { require(_isApprovedOrOwner(_msgSender(), tokenId), 'A: you shall not pass (TF)'); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), 'A: you shall not pass (STF)'); _safeTransfer(from, to, tokenId, _data); } // internal functions function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), 'A: send to fucking contract'); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view Exists(tokenId) returns (bool) { address redneck = _rednecks[tokenId]; return (spender == redneck || _tokenApprovals[tokenId] == spender || isApprovedForAll(redneck, spender)); } /** * @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), 'A: you are stupid'); require(_rednecks[tokenId] == address(0), 'A: you are slowpoke'); _rednecks[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 redneck = _rednecks[tokenId]; address victim = _victims[tokenId]; // Clear approvals _approve(redneck, address(0), tokenId); _swearWords[victim] -= 1; delete _rednecks[tokenId]; delete _victims[tokenId]; emit Transfer(victim, 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 { address redneck = _rednecks[tokenId]; address victim = _victims[tokenId]; require(redneck == from, 'A: deceiver'); require(victim == address(0), 'A: swearing already used'); require(to != address(0), 'A: send to hell'); // Clear approvals from the previous owner _approve(redneck, address(0), tokenId); _swearWords[victim] += 1; _victims[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address from, address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(from, to, tokenId); } /** * @dev Find out who the rednecks */ function _getRednecks(uint256 id) internal view virtual returns (address) { return _rednecks[id]; } /** * @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 See {IERC721-transferFrom}./
function transferFrom(address from, address to, uint256 tokenId) external override { require(_isApprovedOrOwner(_msgSender(), tokenId), 'A: you shall not pass (TF)'); _transfer(from, to, tokenId); }
1,762,367
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 13866, 1265, 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, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 3903, 3849, 288, 203, 3639, 2583, 24899, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 1147, 548, 3631, 296, 37, 30, 1846, 24315, 486, 1342, 261, 17963, 2506, 1769, 203, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xe06eda7435ba749b047380ced49121dde93334ae //Contract name: TransferableMeetupToken //Balance: 0 Ether //Verification Date: 8/31/2017 //Transacion Count: 111 // CODE STARTS HERE /* An ERC20 compliant token that is linked to an external identifier. For exmaple, Meetup.com This software 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 MIT Licence for further details. <https://opensource.org/licenses/MIT>. */ pragma solidity ^0.4.15; contract ERC20Token { /* State */ // The Total supply of tokens uint totSupply; /// @return Token symbol string sym; string nam; uint8 public decimals = 0; // Token ownership mapping mapping (address => uint) balance; // Allowances mapping mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed from, address indexed to, uint256 value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval( address indexed owner, address indexed spender, uint256 value); /* Funtions Public */ function symbol() public constant returns (string) { return sym; } function name() public constant returns (string) { return nam; } // Using an explicit getter allows for function overloading function totalSupply() public constant returns (uint) { return totSupply; } // Using an explicit getter allows for function overloading function balanceOf(address holderAddress) public constant returns (uint) { return balance[holderAddress]; } // Using an explicit getter allows for function overloading function allowance(address ownerAddress, address spenderAddress) public constant returns (uint remaining) { return allowed[ownerAddress][spenderAddress]; } // Send amount amount of tokens to address _to // Reentry protection prevents attacks upon the state function transfer(address toAddress, uint256 amount) public { xfer(msg.sender, toAddress, amount); } // Send amount amount of tokens from address _from to address _to // Reentry protection prevents attacks upon the state function transferFrom(address fromAddress, address toAddress, uint256 amount) public { require(amount <= allowed[fromAddress][msg.sender]); allowed[fromAddress][msg.sender] -= amount; xfer(fromAddress, toAddress, amount); } // Process a transfer internally. function xfer(address fromAddress, address toAddress, uint amount) internal { require(amount <= balance[fromAddress]); balance[fromAddress] -= amount; balance[toAddress] += amount; Transfer(fromAddress, toAddress, amount); } // Approves a third-party spender // Reentry protection prevents attacks upon the state function approve(address spender, uint256 amount) public { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); } } contract TransferableMeetupToken is ERC20Token { address owner = msg.sender; function TransferableMeetupToken(string tokenSymbol, string toeknName) { sym = tokenSymbol; nam = toeknName; } event Issue( address indexed toAddress, uint256 amount, string externalId, string reason); event Redeem( address indexed fromAddress, uint256 amount); function issue(address toAddress, uint amount, string externalId, string reason) public { require(owner == msg.sender); totSupply += amount; balance[toAddress] += amount; Issue(toAddress, amount, externalId, reason); Transfer(0x0, toAddress, amount); } function redeem(uint amount) public { require(balance[msg.sender] >= amount); totSupply -= amount; balance[msg.sender] -= amount; Redeem(msg.sender, amount); Transfer(msg.sender, 0x0, amount); } }
Using an explicit getter allows for function overloading
function totalSupply() public constant returns (uint) { return totSupply; }
14,107,897
[ 1, 7736, 392, 5515, 7060, 5360, 364, 445, 1879, 15174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 9997, 3088, 1283, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x771B2c910D76ecf84B100559CF3Ec4cB2e8D4aC5/sources/contracts/messaging/connectors/ConnectorManager.sol
* @notice This is an interface to allow the `Messaging` contract to be used as a `XappConnectionManager` on all router contracts. @dev Each nomad router contract has a `XappConnectionClient`, which references a XappConnectionManager to get the `Home` (outbox) and approved `Replica` (inbox) instances. At any point the client can replace the manager it's pointing to, changing the underlying messaging connection./
abstract contract ConnectorManager is IConnectorManager { pragma solidity 0.8.17; import {IConnectorManager} from "../interfaces/IConnectorManager.sol"; import {IOutbox} from "../interfaces/IOutbox.sol"; constructor() {} function home() public view returns (IOutbox) { return IOutbox(address(this)); } function isReplica(address _potentialReplica) public view returns (bool) { return _potentialReplica == address(this); } }
14,284,515
[ 1, 2503, 353, 392, 1560, 358, 1699, 326, 1375, 23389, 68, 6835, 358, 506, 1399, 487, 279, 1375, 60, 2910, 1952, 1318, 68, 603, 777, 4633, 20092, 18, 225, 8315, 12457, 361, 4633, 6835, 711, 279, 1375, 60, 2910, 1952, 1227, 9191, 1492, 5351, 279, 1139, 2910, 1952, 1318, 358, 336, 326, 1375, 8684, 68, 261, 659, 2147, 13, 471, 20412, 1375, 14222, 68, 261, 267, 2147, 13, 3884, 18, 2380, 1281, 1634, 326, 1004, 848, 1453, 326, 3301, 518, 1807, 17022, 358, 16, 12770, 326, 6808, 17301, 1459, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 15779, 1318, 353, 467, 7487, 1318, 288, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 5666, 288, 45, 7487, 1318, 97, 628, 315, 6216, 15898, 19, 45, 7487, 1318, 18, 18281, 14432, 203, 5666, 288, 45, 1182, 2147, 97, 628, 315, 6216, 15898, 19, 45, 1182, 2147, 18, 18281, 14432, 203, 225, 3885, 1435, 2618, 203, 225, 445, 6382, 1435, 1071, 1476, 1135, 261, 45, 1182, 2147, 13, 288, 203, 565, 327, 467, 1182, 2147, 12, 2867, 12, 2211, 10019, 203, 225, 289, 203, 203, 225, 445, 353, 14222, 12, 2867, 389, 26451, 14222, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 389, 26451, 14222, 422, 1758, 12, 2211, 1769, 203, 225, 289, 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 ]
./full_match/43114/0x327E60E06b6B7999A341d6aB4c90A305A540D7EB/sources/apps/avai/src/contracts/OrcaAdder.sol
* @notice Adds a LP token, to allow transfering @param _seafund The address of the LP token/
function changeSeafund(address _seafund) public onlyOwner { require(_seafund != address(0), 'Seafund cannot be zero address'); seafund = _seafund; }
4,507,805
[ 1, 3655, 279, 511, 52, 1147, 16, 358, 1699, 7412, 310, 225, 389, 307, 1727, 1074, 1021, 1758, 434, 326, 511, 52, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2549, 1761, 1727, 1074, 12, 2867, 389, 307, 1727, 1074, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 24899, 307, 1727, 1074, 480, 1758, 12, 20, 3631, 296, 1761, 1727, 1074, 2780, 506, 3634, 1758, 8284, 203, 565, 695, 1727, 1074, 273, 389, 307, 1727, 1074, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY668() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF856(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER590(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE439(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE165(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM946(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER113(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL275(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER204() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA645() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED90(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER204(); emit OWNERSHIPTRANSFERRED90(address(0), _owner); } function OWNER726() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER38() { //inject NONSTANDARD NAMING require(ISOWNER90(), "Ownable: caller is not the owner"); _; } function ISOWNER90() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER204() == _owner; } function RENOUNCEOWNERSHIP524() public ONLYOWNER38 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED90(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP660(address newOwner) public ONLYOWNER38 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP31(newOwner); } function _TRANSFEROWNERSHIP31(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED90(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY668() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF856(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER590(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER132(_MSGSENDER204(), recipient, amount); return true; } function ALLOWANCE439(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE165(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE48(_MSGSENDER204(), spender, amount); return true; } function TRANSFERFROM946(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER132(sender, recipient, amount); _APPROVE48(sender, _MSGSENDER204(), _allowances[sender][_MSGSENDER204()].SUB641(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE241(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].ADD348(addedValue)); return true; } function DECREASEALLOWANCE811(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE48(_MSGSENDER204(), spender, _allowances[_MSGSENDER204()][spender].SUB641(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER132(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB641(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD348(amount); emit TRANSFER113(sender, recipient, amount); } function _MINT225(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD348(amount); _balances[account] = _balances[account].ADD348(amount); emit TRANSFER113(address(0), account, amount); } function _BURN186(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB641(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB641(amount); emit TRANSFER113(account, address(0), amount); } function _APPROVE48(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL275(owner, spender, amount); } function _BURNFROM442(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN186(account, amount); _APPROVE48(account, _MSGSENDER204(), _allowances[account][_MSGSENDER204()].SUB641(amount, "ERC20: burn amount exceeds allowance")); } } 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 NAME591() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL151() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS443() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD348(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB641(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB641(a, b, "SafeMath: subtraction overflow"); } function SUB641(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 MUL714(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV963(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV963(a, b, "SafeMath: division by zero"); } function DIV963(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD537(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD537(a, b, "SafeMath: modulo by zero"); } function MOD537(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT792(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE613(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE471(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER595(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFER590.selector, to, value)); } function SAFETRANSFERFROM895(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.TRANSFERFROM946.selector, from, to, value)); } function SAFEAPPROVE173(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE439(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, value)); } function SAFEINCREASEALLOWANCE700(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE439(address(this), spender).ADD348(value); CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE390(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE439(address(this), spender).SUB641(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN929(token, abi.encodeWithSelector(token.APPROVE165.selector, spender, newAllowance)); } function CALLOPTIONALRETURN929(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT792(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Controller { function WITHDRAW362(address, uint) external; //inject NONSTANDARD NAMING function BALANCEOF856(address) external view returns (uint); //inject NONSTANDARD NAMING function EARN394(address, uint) external; //inject NONSTANDARD NAMING function WANT709(address) external view returns (address); //inject NONSTANDARD NAMING } interface Aave { function BORROW427(address _reserve, uint _amount, uint _interestRateModel, uint16 _referralCode) external; //inject NONSTANDARD NAMING function SETUSERUSERESERVEASCOLLATERAL395(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING function REPAY171(address _reserve, uint _amount, address payable _onBehalfOf) external payable; //inject NONSTANDARD NAMING function GETUSERACCOUNTDATA396(address _user) //inject NONSTANDARD NAMING external view returns ( uint totalLiquidityETH, uint totalCollateralETH, uint totalBorrowsETH, uint totalFeesETH, uint availableBorrowsETH, uint currentLiquidationThreshold, uint ltv, uint healthFactor ); function GETUSERRESERVEDATA201(address _reserve, address _user) //inject NONSTANDARD NAMING external view returns ( uint currentATokenBalance, uint currentBorrowBalance, uint principalBorrowBalance, uint borrowRateMode, uint borrowRate, uint liquidityRate, uint originationFee, uint variableBorrowIndex, uint lastUpdateTimestamp, bool usageAsCollateralEnabled ); } interface AaveToken { function UNDERLYINGASSETADDRESS967() external view returns (address); //inject NONSTANDARD NAMING } interface Oracle { function GETASSETPRICE895(address reserve) external view returns (uint); //inject NONSTANDARD NAMING function LATESTANSWER820() external view returns (uint); //inject NONSTANDARD NAMING } interface LendingPoolAddressesProvider { function GETLENDINGPOOL689() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE785() external view returns (address); //inject NONSTANDARD NAMING function GETPRICEORACLE709() external view returns (address); //inject NONSTANDARD NAMING } contract yDelegatedVault is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; address public governance; address public controller; uint public insurance; uint public healthFactor = 4; address public constant aave533 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING constructor (address _token, address _controller) public ERC20Detailed( string(abi.encodePacked("yearn ", ERC20Detailed(_token).NAME591())), string(abi.encodePacked("y", ERC20Detailed(_token).SYMBOL151())), ERC20Detailed(_token).DECIMALS443() ) { token = IERC20(_token); governance = msg.sender; controller = _controller; } function DEBT414() public view returns (uint) { //inject NONSTANDARD NAMING address _reserve = Controller(controller).WANT709(address(this)); (,uint currentBorrowBalance,,,,,,,,) = Aave(GETAAVE93()).GETUSERRESERVEDATA201(_reserve, address(this)); return currentBorrowBalance; } function CREDIT327() public view returns (uint) { //inject NONSTANDARD NAMING return Controller(controller).BALANCEOF856(address(this)); } // % of tokens locked and cannot be withdrawn per user // this is impermanent locked, unless the debt out accrues the strategy function LOCKED694() public view returns (uint) { //inject NONSTANDARD NAMING return CREDIT327().MUL714(1e18).DIV963(DEBT414()); } function DEBTSHARE933(address _lp) public view returns (uint) { //inject NONSTANDARD NAMING return DEBT414().MUL714(BALANCEOF856(_lp)).MUL714(TOTALSUPPLY668()); } function GETAAVE93() public view returns (address) { //inject NONSTANDARD NAMING return LendingPoolAddressesProvider(aave533).GETLENDINGPOOL689(); } function GETAAVECORE229() public view returns (address) { //inject NONSTANDARD NAMING return LendingPoolAddressesProvider(aave533).GETLENDINGPOOLCORE785(); } function SETHEALTHFACTOR690(uint _hf) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); healthFactor = _hf; } function ACTIVATE169() public { //inject NONSTANDARD NAMING Aave(GETAAVE93()).SETUSERUSERESERVEASCOLLATERAL395(UNDERLYING289(), true); } function REPAY171(address reserve, uint amount) public { //inject NONSTANDARD NAMING // Required for certain stable coins (USDT for example) IERC20(reserve).APPROVE165(address(GETAAVECORE229()), 0); IERC20(reserve).APPROVE165(address(GETAAVECORE229()), amount); Aave(GETAAVE93()).REPAY171(reserve, amount, address(uint160(address(this)))); } function REPAYALL522() public { //inject NONSTANDARD NAMING address _reserve = RESERVE164(); uint _amount = IERC20(_reserve).BALANCEOF856(address(this)); REPAY171(_reserve, _amount); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function HARVEST865(address reserve, uint amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).SAFETRANSFER595(controller, amount); } // Ignore insurance fund for balance calculations function BALANCE541() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF856(address(this)).SUB641(insurance); } function SETCONTROLLER494(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } function GETAAVEORACLE538() public view returns (address) { //inject NONSTANDARD NAMING return LendingPoolAddressesProvider(aave533).GETPRICEORACLE709(); } function GETRESERVEPRICEETH945(address reserve) public view returns (uint) { //inject NONSTANDARD NAMING return Oracle(GETAAVEORACLE538()).GETASSETPRICE895(reserve); } function SHOULDREBALANCE804() external view returns (bool) { //inject NONSTANDARD NAMING return (OVER549() > 0); } function OVER549() public view returns (uint) { //inject NONSTANDARD NAMING OVER549(0); } function GETUNDERLYINGPRICEETH537(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING return _amount.MUL714(GETUNDERLYINGPRICE909()).DIV963(uint(10)**ERC20Detailed(address(token)).DECIMALS443()); // Calculate the amount we are withdrawing in ETH } function OVER549(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING address _reserve = RESERVE164(); uint _eth = GETUNDERLYINGPRICEETH537(_amount); (uint _maxSafeETH,uint _totalBorrowsETH,) = MAXSAFEETH837(); _maxSafeETH = _maxSafeETH.MUL714(105).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop if (_eth > _maxSafeETH) { _maxSafeETH = 0; } else { _maxSafeETH = _maxSafeETH.SUB641(_eth); // Add the ETH we are withdrawing } if (_maxSafeETH < _totalBorrowsETH) { uint _over = _totalBorrowsETH.MUL714(_totalBorrowsETH.SUB641(_maxSafeETH)).DIV963(_totalBorrowsETH); _over = _over.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515()); return _over; } else { return 0; } } function _REBALANCE677(uint _amount) internal { //inject NONSTANDARD NAMING uint _over = OVER549(_amount); if (_over > 0) { Controller(controller).WITHDRAW362(address(this), _over); REPAYALL522(); } } function REBALANCE176() external { //inject NONSTANDARD NAMING _REBALANCE677(0); } function CLAIMINSURANCE254() external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); token.SAFETRANSFER595(controller, insurance); insurance = 0; } function MAXSAFEETH837() public view returns (uint maxBorrowsETH, uint totalBorrowsETH, uint availableBorrowsETH) { //inject NONSTANDARD NAMING (,,uint _totalBorrowsETH,,uint _availableBorrowsETH,,,) = Aave(GETAAVE93()).GETUSERACCOUNTDATA396(address(this)); uint _maxBorrowETH = (_totalBorrowsETH.ADD348(_availableBorrowsETH)); return (_maxBorrowETH.DIV963(healthFactor), _totalBorrowsETH, _availableBorrowsETH); } function SHOULDBORROW22() external view returns (bool) { //inject NONSTANDARD NAMING return (AVAILABLETOBORROWRESERVE235() > 0); } function AVAILABLETOBORROWETH693() public view returns (uint) { //inject NONSTANDARD NAMING (uint _maxSafeETH,uint _totalBorrowsETH, uint _availableBorrowsETH) = MAXSAFEETH837(); _maxSafeETH = _maxSafeETH.MUL714(95).DIV963(100); // 5% buffer so we don't go into a earn/rebalance loop if (_maxSafeETH > _totalBorrowsETH) { return _availableBorrowsETH.MUL714(_maxSafeETH.SUB641(_totalBorrowsETH)).DIV963(_availableBorrowsETH); } else { return 0; } } function AVAILABLETOBORROWRESERVE235() public view returns (uint) { //inject NONSTANDARD NAMING address _reserve = RESERVE164(); uint _available = AVAILABLETOBORROWETH693(); if (_available > 0) { return _available.MUL714(uint(10)**ERC20Detailed(_reserve).DECIMALS443()).DIV963(GETRESERVEPRICE515()); } else { return 0; } } function GETRESERVEPRICE515() public view returns (uint) { //inject NONSTANDARD NAMING return GETRESERVEPRICEETH945(RESERVE164()); } function GETUNDERLYINGPRICE909() public view returns (uint) { //inject NONSTANDARD NAMING return GETRESERVEPRICEETH945(UNDERLYING289()); } function EARN394() external { //inject NONSTANDARD NAMING address _reserve = RESERVE164(); uint _borrow = AVAILABLETOBORROWRESERVE235(); if (_borrow > 0) { Aave(GETAAVE93()).BORROW427(_reserve, _borrow, 2, 7); } //rebalance here uint _balance = IERC20(_reserve).BALANCEOF856(address(this)); if (_balance > 0) { IERC20(_reserve).SAFETRANSFER595(controller, _balance); Controller(controller).EARN394(address(this), _balance); } } function DEPOSITALL399() external { //inject NONSTANDARD NAMING DEPOSIT764(token.BALANCEOF856(msg.sender)); } function DEPOSIT764(uint _amount) public { //inject NONSTANDARD NAMING uint _pool = BALANCE541(); token.SAFETRANSFERFROM895(msg.sender, address(this), _amount); // 0.5% of deposits go into an insurance fund incase of negative profits to protect withdrawals // At a 4 health factor, this is a -2% position uint _insurance = _amount.MUL714(50).DIV963(10000); _amount = _amount.SUB641(_insurance); insurance = insurance.ADD348(_insurance); //Controller can claim insurance to liquidate to cover interest uint shares = 0; if (TOTALSUPPLY668() == 0) { shares = _amount; ACTIVATE169(); } else { shares = (_amount.MUL714(TOTALSUPPLY668())).DIV963(_pool); } _MINT225(msg.sender, shares); } function RESERVE164() public view returns (address) { //inject NONSTANDARD NAMING return Controller(controller).WANT709(address(this)); } function UNDERLYING289() public view returns (address) { //inject NONSTANDARD NAMING return AaveToken(address(token)).UNDERLYINGASSETADDRESS967(); } function WITHDRAWALL686() public { //inject NONSTANDARD NAMING WITHDRAW362(BALANCEOF856(msg.sender)); } // Calculates in impermanent lock due to debt function MAXWITHDRAWAL697(address account) public view returns (uint) { //inject NONSTANDARD NAMING uint _balance = BALANCEOF856(account); uint _safeWithdraw = _balance.MUL714(LOCKED694()).DIV963(1e18); if (_safeWithdraw > _balance) { return _balance; } else { uint _diff = _balance.SUB641(_safeWithdraw); return _balance.SUB641(_diff.MUL714(2)); // technically 150%, not 200%, but adding buffer } } function SAFEWITHDRAW954() external { //inject NONSTANDARD NAMING WITHDRAW362(MAXWITHDRAWAL697(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function WITHDRAW362(uint _shares) public { //inject NONSTANDARD NAMING uint r = (BALANCE541().MUL714(_shares)).DIV963(TOTALSUPPLY668()); _BURN186(msg.sender, _shares); _REBALANCE677(r); token.SAFETRANSFER595(msg.sender, r); } function GETPRICEPERFULLSHARE836() external view returns (uint) { //inject NONSTANDARD NAMING return BALANCE541().MUL714(1e18).DIV963(TOTALSUPPLY668()); } }
inject NONSTANDARD NAMING
function TRANSFER590(address recipient, uint256 amount) external returns (bool);
12,699,319
[ 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, 4235, 17598, 6162, 20, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 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 ]
./partial_match/1/0xF28871fcD2e6E9224D4b5E9050405Af59A452e5D/sources/WBTC.sol
Buy FeeSell FeeOriginal Fee
contract WBTC is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Wrapped Bitcoin"; string private constant _symbol = "WBTC"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _redisFeeOnBuy = 0; uint256 private _taxFeeOnBuy = 20; uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 20; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xB121235f2CE6FF8F04D77f03f80A3bbF674192d0); address payable private _marketingAddress = payable(0xB121235f2CE6FF8F04D77f03f80A3bbF674192d0); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true; bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true; bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true; bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true; bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true; bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _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 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } }
11,009,380
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 678, 38, 15988, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 17665, 24420, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 59, 38, 15988, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 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, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 2130, 11706, 380, 1728, 636, 29, 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, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 4200, 31, 203, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 273, 4200, 31, 203, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 273, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-01-05 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/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 OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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 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; } // File: contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Copyright (c) 2020 Base Protocol, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.12; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/ERC20UpgradeSafe.sol pragma solidity 0.6.12; /** * @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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view 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 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 { } uint256[44] private __gap; } // File: contracts/interfaces/ERC677.sol pragma solidity 0.6.12; abstract contract ERC677 { function transfer(address to, uint256 value) public virtual returns (bool); function transferAndCall(address to, uint value, bytes memory data) public virtual returns (bool success); // event Transfer(address indexed from, address indexed to, uint value, bytes data); } // File: contracts/interfaces/ERC677Receiver.sol pragma solidity 0.6.12; abstract contract ERC677Receiver { function onTokenTransfer(address _sender, uint _value, bytes memory _data) virtual public; } // File: contracts/ERC677Token.sol pragma solidity 0.6.12; abstract contract ERC677Token is ERC677 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes memory _data) public override returns (bool success) { transfer(_to, _value); // emit Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } function contractFallback(address _to, uint _value, bytes memory _data) private { ERC677Receiver receiver = ERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private view returns (bool hasCode) { uint length; // solhint-disable-next-line no-inline-assembly assembly { length := extcodesize(_addr) } return length > 0; } } // File: contracts/XdefToken.sol pragma solidity 0.6.12; /** * @title Xdef ERC20 token * @dev This is part of an implementation of the Xdef Index Fund protocol. * Xdef is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * Xdef balances are internally represented with a hidden denomination, 'shares'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'shares' and the public 'Xdef'. */ contract XdefToken is ERC20UpgradeSafe, ERC677Token, OwnableUpgradeSafe { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of shares that equals 1 Xdef. // The inverse rate must not be used--totalShares is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert shares to Xdef instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Share balances converted into XdefToken are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x XdefToken to address 'B'. A's resulting external balance will // be decreased by precisely x XdefToken, and B's external balance will be precisely // increased by x XdefToken. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); event LogUserBanStatusUpdated(address user, bool banned); // Used for authentication address public monetaryPolicy; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_SUPPLY = 19067164 * 10**DECIMALS; uint256 private constant INITIAL_SHARES = (MAX_UINT256 / (10 ** 36)) - ((MAX_UINT256 / (10 ** 36)) % INITIAL_SUPPLY); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalShares; uint256 private _totalSupply; uint256 private _sharesPerXdef; mapping(address => uint256) private _shareBalances; mapping(address => bool) public bannedUsers; // This is denominated in XdefToken, because the shares-Xdef conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedXdef; bool public transfersPaused; bool public rebasesPaused; mapping(address => bool) public transferPauseExemptList; function setTransfersPaused(bool _transfersPaused) public onlyOwner { transfersPaused = _transfersPaused; } function setTransferPauseExempt(address user, bool exempt) public onlyOwner { if (exempt) { transferPauseExemptList[user] = true; } else { delete transferPauseExemptList[user]; } } function setRebasesPaused(bool _rebasesPaused) public onlyOwner { rebasesPaused = _rebasesPaused; } /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } /** * @dev Notifies XdefToken contract about a new rebase cycle. * @param supplyDelta The number of new Xdef tokens to add into circulation via expansion. * @return The total number of Xdef after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256) { require(msg.sender == monetaryPolicy, "only monetary policy"); require(!rebasesPaused, "rebases paused"); if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _sharesPerXdef = _totalShares.div(_totalSupply); // From this point forward, _sharesPerXdef is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _sharesPerXdef // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(totalShares - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. emit LogRebase(epoch, _totalSupply); return _totalSupply; } function totalShares() public view returns (uint256) { return _totalShares; } function sharesOf(address user) public view returns (uint256) { return _shareBalances[user]; } function mintShares(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); _shareBalances[recipient] = _shareBalances[recipient].add(amount); _totalShares = _totalShares.add(amount); } function burnShares(address recipient, uint256 amount) public { require(msg.sender == monetaryPolicy, "forbidden"); require(_shareBalances[recipient] >= amount, "amount"); _shareBalances[recipient] = _shareBalances[recipient].sub(amount); _totalShares = _totalShares.sub(amount); } function initialize() public initializer { __ERC20_init("Xdef finance", "Xdef"); _setupDecimals(uint8(DECIMALS)); __Ownable_init(); _totalShares = INITIAL_SHARES; _totalSupply = INITIAL_SUPPLY; _shareBalances[owner()] = _totalShares; _sharesPerXdef = _totalShares.div(_totalSupply); // Ban the Kucoin hacker bannedUsers[0xeB31973E0FeBF3e3D7058234a5eBbAe1aB4B8c23] = true; emit Transfer(address(0x0), owner(), _totalSupply); } function setUserBanStatus(address user, bool banned) public onlyOwner { if (banned) { bannedUsers[user] = true; } else { delete bannedUsers[user]; } emit LogUserBanStatusUpdated(user, banned); } /** * @return The total number of Xdef. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public override view returns (uint256) { return _shareBalances[who].div(_sharesPerXdef); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override(ERC20UpgradeSafe, ERC677) validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 shareValue = value.mul(_sharesPerXdef); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public override view returns (uint256) { return _allowedXdef[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public override validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedXdef[from][msg.sender] = _allowedXdef[from][msg.sender].sub(value); uint256 shareValue = value.mul(_sharesPerXdef); _shareBalances[from] = _shareBalances[from].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedXdef[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); _allowedXdef[msg.sender][spender] = _allowedXdef[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedXdef[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 oldValue = _allowedXdef[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedXdef[msg.sender][spender] = 0; } else { _allowedXdef[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedXdef[msg.sender][spender]); return true; } }
* @dev Transfer tokens to a specified address. @param to The address to transfer to. @param value The amount to be transferred. @return True on success, false otherwise./
function transfer(address to, uint256 value) public override(ERC20UpgradeSafe, ERC677) validRecipient(to) returns (bool) { require(bannedUsers[msg.sender] == false, "you are banned"); require(!transfersPaused || transferPauseExemptList[msg.sender], "paused"); uint256 shareValue = value.mul(_sharesPerXdef); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; }
7,821,813
[ 1, 5912, 2430, 358, 279, 1269, 1758, 18, 225, 358, 1021, 1758, 358, 7412, 358, 18, 225, 460, 1021, 3844, 358, 506, 906, 4193, 18, 327, 1053, 603, 2216, 16, 629, 3541, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 203, 3639, 1071, 203, 3639, 3849, 12, 654, 39, 3462, 10784, 9890, 16, 4232, 39, 26, 4700, 13, 203, 3639, 923, 18241, 12, 869, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 70, 10041, 6588, 63, 3576, 18, 15330, 65, 422, 629, 16, 315, 19940, 854, 324, 10041, 8863, 203, 3639, 2583, 12, 5, 2338, 18881, 28590, 747, 7412, 19205, 424, 5744, 682, 63, 3576, 18, 15330, 6487, 315, 8774, 3668, 8863, 203, 203, 3639, 2254, 5034, 7433, 620, 273, 460, 18, 16411, 24899, 30720, 2173, 60, 536, 1769, 203, 3639, 389, 14419, 38, 26488, 63, 3576, 18, 15330, 65, 273, 389, 14419, 38, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 14419, 620, 1769, 203, 3639, 389, 14419, 38, 26488, 63, 869, 65, 273, 389, 14419, 38, 26488, 63, 869, 8009, 1289, 12, 14419, 620, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import './CGTokenBase.sol'; import './CGMintable.sol'; /** * @title CampGenie Mintable token base * @dev This contract adds support for minting tokens to CGTokenBase. * Based on code by OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/MintableToken.sol */ contract CGMintableTokenBase is CGTokenBase, CGMintable { /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract. * Adds the owner to the list of minters with a limit of 1/10 of the initial supply. * @param initialSupplyValue The initial supply of tokens, in units of tokens. * @param tokenDecimals The number of decimals in the currency; controls how finely a token is split. * @param tokenName The token name (leave empty to use the default value). * @param tokenSymbol The token symbol (leave empty to use the default value). */ constructor( uint256 initialSupplyValue, uint8 tokenDecimals, string tokenName, string tokenSymbol ) public CGTokenBase(initialSupplyValue, tokenDecimals, tokenName, tokenSymbol) { registerMinter(owner, totalSupply / 10); } /** * Function to mint tokens. * @dev The call fails if `_amount` is larger than the current mint limit for the caller. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. */ function mint(address _to, uint256 _amount) mintEnabled activeMinter(msg.sender) public { Minter storage m = minters[msg.sender]; uint256 minted = m.minted.add(_amount); require (minted <= m.max); m.minted = minted; totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); } }
* Function to mint tokens. @dev The call fails if `_amount` is larger than the current mint limit for the caller. @param _to The address that will receive the minted tokens. @param _amount The amount of tokens to mint./
function mint(address _to, uint256 _amount) mintEnabled activeMinter(msg.sender) public { Minter storage m = minters[msg.sender]; uint256 minted = m.minted.add(_amount); require (minted <= m.max); m.minted = minted; totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); }
1,758,331
[ 1, 2083, 358, 312, 474, 2430, 18, 225, 1021, 745, 6684, 309, 1375, 67, 8949, 68, 353, 10974, 2353, 326, 783, 312, 474, 1800, 364, 326, 4894, 18, 225, 389, 869, 1021, 1758, 716, 903, 6798, 326, 312, 474, 329, 2430, 18, 225, 389, 8949, 1021, 3844, 434, 2430, 358, 312, 474, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 312, 474, 1526, 2695, 49, 2761, 12, 3576, 18, 15330, 13, 1071, 288, 203, 3639, 490, 2761, 2502, 312, 273, 1131, 5432, 63, 3576, 18, 15330, 15533, 203, 3639, 2254, 5034, 312, 474, 329, 273, 312, 18, 81, 474, 329, 18, 1289, 24899, 8949, 1769, 203, 3639, 2583, 261, 81, 474, 329, 1648, 312, 18, 1896, 1769, 203, 540, 203, 3639, 312, 18, 81, 474, 329, 273, 312, 474, 329, 31, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1289, 24899, 8949, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 8949, 1769, 203, 203, 3639, 3626, 490, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; pragma experimental ABIEncoderV2; // File: @axie/contract-library/contracts/access/HasAdmin.sol contract HasAdmin { event AdminChanged(address indexed _oldAdmin, address indexed _newAdmin); event AdminRemoved(address indexed _oldAdmin); address public admin; modifier onlyAdmin { require(true); _; } constructor() internal { admin = msg.sender; emit AdminChanged(address(0), admin); } function changeAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); emit AdminChanged(admin, _newAdmin); admin = _newAdmin; } function removeAdmin() external onlyAdmin { emit AdminRemoved(admin); admin = address(0); } } // File: @axie/contract-library/contracts/lifecycle/Pausable.sol contract Pausable is HasAdmin { event Paused(); event Unpaused(); bool public paused; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() public onlyAdmin whenNotPaused { paused = true; emit Paused(); } function unpause() public onlyAdmin whenPaused { paused = false; emit Unpaused(); } } // File: @axie/contract-library/contracts/math/Math.sol library Math { function max(uint256 a, uint256 b) internal pure returns (uint256 c) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256 c) { return a < b ? a : b; } } // File: @axie/contract-library/contracts/token/erc20/IERC20.sol interface IERC20 { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function totalSupply() external view returns (uint256 _supply); function balanceOf(address _owner) external view returns (uint256 _balance); function approve(address _spender, uint256 _value) external returns (bool _success); function allowance(address _owner, address _spender) external view returns (uint256 _value); function transfer(address _to, uint256 _value) external returns (bool _success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool _success); } // File: @axie/contract-library/contracts/ownership/Withdrawable.sol contract Withdrawable is HasAdmin { function withdrawEther() external onlyAdmin { msg.sender.transfer(address(this).balance); msg.sender.transfer(address(this).balance); } //injected WASTEFUL CONTRACT function withdrawToken(IERC20 _token) external onlyAdmin { require(_token.transfer(msg.sender, _token.balanceOf(address(this)))); } } // File: @axie/contract-library/contracts/token/erc20/IERC20Receiver.sol interface IERC20Receiver { function receiveApproval( address _from, uint256 _value, address _tokenAddress, bytes calldata _data ) external; } // File: @axie/contract-library/contracts/token/swap/IKyber.sol interface IKyber { function getExpectedRate( address _src, address _dest, uint256 _srcAmount ) external view returns ( uint256 _expectedRate, uint256 _slippageRate ); function trade( address _src, uint256 _maxSrcAmount, address _dest, address payable _receiver, uint256 _maxDestAmount, uint256 _minConversionRate, address _wallet ) external payable returns (uint256 _destAmount); } // File: @axie/contract-library/contracts/math/SafeMath.sol library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { // Since Solidity automatically asserts when dividing by 0, // but we only need it to revert. require(b > 0); return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256 c) { // Same reason as `div`. require(b > 0); return a % b; } function ceilingDiv(uint256 a, uint256 b) internal pure returns (uint256 c) { return add(div(a, b), mod(a, b) > 0 ? 1 : 0); } function subU64(uint64 a, uint64 b) internal pure returns (uint64 c) { require(b <= a); return a - b; } function addU8(uint8 a, uint8 b) internal pure returns (uint8 c) { c = a + b; require(c >= a); } } // File: @axie/contract-library/contracts/token/erc20/IERC20Detailed.sol interface IERC20Detailed { function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function decimals() external view returns (uint8 _decimals); } // File: @axie/contract-library/contracts/token/swap/KyberTokenDecimals.sol contract KyberTokenDecimals { using SafeMath for uint256; address public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function _getTokenDecimals(address _token) internal view returns (uint8 _decimals) { return _token != ethAddress ? IERC20Detailed(_token).decimals() : 18; } function _fixTokenDecimals( address _src, address _dest, uint256 _unfixedDestAmount, bool _ceiling ) internal view returns (uint256 _destTokenAmount) { uint256 _unfixedDecimals = _getTokenDecimals(_src) + 18; // Kyber by default returns rates with 18 decimals. uint256 _decimals = _getTokenDecimals(_dest); if (_unfixedDecimals > _decimals) { // Divide token amount by 10^(_unfixedDecimals - _decimals) to reduce decimals. if (_ceiling) { return _unfixedDestAmount.ceilingDiv(10 ** (_unfixedDecimals - _decimals)); } else { return _unfixedDestAmount.div(10 ** (_unfixedDecimals - _decimals)); } } else { // Multiply token amount with 10^(_decimals - _unfixedDecimals) to increase decimals. return _unfixedDestAmount.mul(10 ** (_decimals - _unfixedDecimals)); } } } // File: @axie/contract-library/contracts/token/swap/KyberAdapter.sol contract KyberAdapter is KyberTokenDecimals { IKyber public kyber = IKyber(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); function () external payable { // Commented out since Kyber sent Ether from their main contract, // The contract we have here is their proxy contract. // require(msg.sender == address(kyber)); } function _getConversionRate( address _src, uint256 _srcAmount, address _dest ) internal view returns ( uint256 _expectedRate, uint256 _slippageRate ) { return kyber.getExpectedRate(_src, _dest, _srcAmount); } function _convertToken( address _src, uint256 _srcAmount, address _dest ) internal view returns ( uint256 _expectedAmount, uint256 _slippageAmount ) { (uint256 _expectedRate, uint256 _slippageRate) = _getConversionRate(_src, _srcAmount, _dest); return ( _fixTokenDecimals(_src, _dest, _srcAmount.mul(_expectedRate), false), _fixTokenDecimals(_src, _dest, _srcAmount.mul(_slippageRate), false) ); } function _getTokenBalance(address _token, address _account) internal view returns (uint256 _balance) { return _token != ethAddress ? IERC20(_token).balanceOf(_account) : _account.balance; } function _swapToken( address _src, uint256 _maxSrcAmount, address _dest, uint256 _maxDestAmount, uint256 _minConversionRate, address payable _initiator, address payable _receiver ) internal returns ( uint256 _srcAmount, uint256 _destAmount ) { require(_src != _dest); require(_src == ethAddress ? msg.value >= _maxSrcAmount : msg.value == 0); // Prepare for handling back the change if there is any. uint256 _balanceBefore = _getTokenBalance(_src, address(this)); if (_src != ethAddress) { require(IERC20(_src).transferFrom(_initiator, address(this), _maxSrcAmount)); require(IERC20(_src).approve(address(kyber), _maxSrcAmount)); } else { // Since we are going to transfer the source amount to Kyber. _balanceBefore = _balanceBefore.sub(_maxSrcAmount); } _destAmount = kyber.trade.value( _src == ethAddress ? _maxSrcAmount : 0 )( _src, _maxSrcAmount, _dest, _receiver, _maxDestAmount, _minConversionRate, address(0) ); uint256 _balanceAfter = _getTokenBalance(_src, address(this)); _srcAmount = _maxSrcAmount; // Handle back the change, if there is any, to the message sender. if (_balanceAfter > _balanceBefore) { uint256 _change = _balanceAfter - _balanceBefore; _srcAmount = _srcAmount.sub(_change); if (_src != ethAddress) { require(IERC20(_src).transfer(_initiator, _change)); } else { _initiator.transfer(_change); } } } } // File: @axie/contract-library/contracts/token/swap/KyberCustomTokenRates.sol contract KyberCustomTokenRates is HasAdmin, KyberAdapter { struct Rate { address quote; uint256 value; } event CustomTokenRateUpdated( address indexed _tokenAddress, address indexed _quoteTokenAddress, uint256 _rate ); mapping (address => Rate) public customTokenRate; function _hasCustomTokenRate(address _tokenAddress) internal view returns (bool _correct) { return customTokenRate[_tokenAddress].value > 0; } function _setCustomTokenRate(address _tokenAddress, address _quoteTokenAddress, uint256 _rate) internal { require(_rate > 0); customTokenRate[_tokenAddress] = Rate({ quote: _quoteTokenAddress, value: _rate }); emit CustomTokenRateUpdated(_tokenAddress, _quoteTokenAddress, _rate); } // solium-disable-next-line security/no-assign-params function _getConversionRate( address _src, uint256 _srcAmount, address _dest ) internal view returns ( uint256 _expectedRate, uint256 _slippageRate ) { uint256 _numerator = 1; uint256 _denominator = 1; if (_hasCustomTokenRate(_src)) { Rate storage _rate = customTokenRate[_src]; _src = _rate.quote; _srcAmount = _srcAmount.mul(_rate.value).div(10**18); _numerator = _rate.value; _denominator = 10**18; } if (_hasCustomTokenRate(_dest)) { Rate storage _rate = customTokenRate[_dest]; _dest = _rate.quote; // solium-disable-next-line whitespace if (_numerator == 1) { _numerator = 10**18; } _denominator = _rate.value; } if (_src != _dest) { (_expectedRate, _slippageRate) = super._getConversionRate(_src, _srcAmount, _dest); } else { _expectedRate = _slippageRate = 10**18; } return ( _expectedRate.mul(_numerator).div(_denominator), _slippageRate.mul(_numerator).div(_denominator) ); } function _swapToken( address _src, uint256 _maxSrcAmount, address _dest, uint256 _maxDestAmount, uint256 _minConversionRate, address payable _initiator, address payable _receiver ) internal returns ( uint256 _srcAmount, uint256 _destAmount ) { if (_hasCustomTokenRate(_src) || _hasCustomTokenRate(_dest)) { require(_src == ethAddress ? msg.value >= _maxSrcAmount : msg.value == 0); require(_receiver == address(this)); (uint256 _expectedRate, ) = _getConversionRate(_src, _srcAmount, _dest); require(_expectedRate >= _minConversionRate); _srcAmount = _maxSrcAmount; _destAmount = _fixTokenDecimals(_src, _dest, _srcAmount.mul(_expectedRate), false); if (_destAmount > _maxDestAmount) { _destAmount = _maxDestAmount; _srcAmount = _fixTokenDecimals(_dest, _src, _destAmount.mul(10**36).ceilingDiv(_expectedRate), true); // To avoid rounding error. if (_srcAmount > _maxSrcAmount) { _srcAmount = _maxSrcAmount; } } if (_src != ethAddress) { require(IERC20(_src).transferFrom(_initiator, address(this), _srcAmount)); } else if (msg.value > _srcAmount) { _initiator.transfer(msg.value - _srcAmount); } return (_srcAmount, _destAmount); } return super._swapToken( _src, _maxSrcAmount, _dest, _maxDestAmount, _minConversionRate, _initiator, _receiver ); } } // File: @axie/contract-library/contracts/util/AddressUtils.sol library AddressUtils { function toPayable(address _address) internal pure returns (address payable _payable) { return address(uint160(_address)); } function isContract(address _address) internal view returns (bool _correct) { uint256 _size; // solium-disable-next-line security/no-inline-assembly assembly { _size := extcodesize(_address) } return _size > 0; } } // File: contracts/land/sale/LandSale.sol contract LandSale_v2 is Pausable, Withdrawable, KyberCustomTokenRates, IERC20Receiver { using AddressUtils for address; enum ChestType { Savannah, Forest, Arctic, Mystic } event ChestPurchased( ChestType indexed _chestType, uint256 _chestAmount, address indexed _tokenAddress, uint256 _tokenAmount, uint256 _totalPrice, uint256 _lunaCashbackAmount, address _buyer, // Ran out of indexed fields. address indexed _owner ); event ReferralRewarded( address indexed _referrer, uint256 _referralReward ); event ReferralPercentageUpdated( address indexed _referrer, uint256 _percentage ); address public daiAddress = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359; address public loomAddress = 0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0; uint256 public startedAt = 1548165600; // Tuesday, January 22, 2019 2:00:00 PM GMT+00:00 uint256 public endedAt = 1563804000; // Monday, July 22, 2019 2:00:00 PM GMT+00:00 mapping (uint8 => uint256) public chestCap; uint256 public savannahChestPrice = 0.05 ether; uint256 public forestChestPrice = 0.16 ether; uint256 public arcticChestPrice = 0.45 ether; uint256 public mysticChestPrice = 1.00 ether; uint256 public initialDiscountPercentage = 1000; // 10%. uint256 public initialDiscountDays = 10 days; uint256 public cashbackPercentage = 1000; // 10%. uint256 public defaultReferralPercentage = 1000; // 10%. mapping (address => uint256) public referralPercentage; IERC20 public lunaContract; address public lunaBankAddress; modifier whenInSale { // solium-disable-next-line security/no-block-members require(now >= startedAt && now <= endedAt); _; } constructor(IERC20 _lunaContract, address _lunaBankAddress) public { // 1 LUNA = 1/10 DAI (rate has 18 decimals). _setCustomTokenRate(address(_lunaContract), daiAddress, 10**17); lunaContract = _lunaContract; lunaBankAddress = _lunaBankAddress; setChestCap([uint256(5349), 5359, 4171, 2338]); } function getPrice( ChestType _chestType, uint256 _chestAmount, address _tokenAddress ) external view returns ( uint256 _tokenAmount, uint256 _minConversionRate ) { uint256 _totalPrice = _getEthPrice(_chestType, _chestAmount, _tokenAddress); if (_tokenAddress != ethAddress) { (_tokenAmount, ) = _convertToken(ethAddress, _totalPrice, _tokenAddress); (, _minConversionRate) = _getConversionRate(_tokenAddress, _tokenAmount, ethAddress); _tokenAmount = _totalPrice.mul(10**36).ceilingDiv(_minConversionRate); _tokenAmount = _fixTokenDecimals(ethAddress, _tokenAddress, _tokenAmount, true); } else { _tokenAmount = _totalPrice; } } function purchase( ChestType _chestType, uint256 _chestAmount, address _tokenAddress, uint256 _maxTokenAmount, uint256 _minConversionRate, address payable _referrer ) external payable whenInSale whenNotPaused { _purchase( _chestType, _chestAmount, _tokenAddress, _maxTokenAmount, _minConversionRate, msg.sender, msg.sender, _referrer ); } function purchaseFor( ChestType _chestType, uint256 _chestAmount, address _tokenAddress, uint256 _maxTokenAmount, uint256 _minConversionRate, address _owner ) external payable whenInSale whenNotPaused { _purchase( _chestType, _chestAmount, _tokenAddress, _maxTokenAmount, _minConversionRate, msg.sender, _owner, msg.sender ); } function receiveApproval( address _from, uint256 _value, address _tokenAddress, bytes calldata /* _data */ ) external whenInSale whenNotPaused { require(msg.sender == _tokenAddress); uint256 _action; ChestType _chestType; uint256 _chestAmount; uint256 _minConversionRate; address payable _referrerOrOwner; // solium-disable-next-line security/no-inline-assembly assembly { _action := calldataload(0xa4) _chestType := calldataload(0xc4) _chestAmount := calldataload(0xe4) _minConversionRate := calldataload(0x104) _referrerOrOwner := calldataload(0x124) } address payable _buyer; address _owner; address payable _referrer; if (_action == 0) { // Purchase. _buyer = _from.toPayable(); _owner = _from; _referrer = _referrerOrOwner; } else if (_action == 1) { // Purchase for. _buyer = _from.toPayable(); _owner = _referrerOrOwner; _referrer = _from.toPayable(); } else { revert(); } _purchase( _chestType, _chestAmount, _tokenAddress, _value, _minConversionRate, _buyer, _owner, _referrer ); } function setReferralPercentages(address[] calldata _referrers, uint256[] calldata _percentage) external onlyAdmin { for (uint256 i = 0; i < _referrers.length; i++) { referralPercentage[_referrers[i]] = _percentage[i]; emit ReferralPercentageUpdated(_referrers[i], _percentage[i]); } } function setCustomTokenRates(address[] memory _tokenAddresses, Rate[] memory _rates) public onlyAdmin { for (uint256 i = 0; i < _tokenAddresses.length; i++) { _setCustomTokenRate(_tokenAddresses[i], _rates[i].quote, _rates[i].value); } } function setChestCap(uint256[4] memory _chestCap) public onlyAdmin { for (uint8 _chestType = 0; _chestType < 4; _chestType++) { chestCap[_chestType] = _chestCap[_chestType]; } } function _getPresentPercentage() internal view returns (uint256 _percentage) { // solium-disable-next-line security/no-block-members uint256 _elapsedDays = (now - startedAt).div(1 days).mul(1 days); return uint256(10000) // 100%. .sub(initialDiscountPercentage) .add( initialDiscountPercentage .mul(Math.min(_elapsedDays, initialDiscountDays)) .div(initialDiscountDays) ); } function _getEthPrice( ChestType _chestType, uint256 _chestAmount, address _tokenAddress ) internal view returns (uint256 _price) { // solium-disable-next-line indentation if (_chestType == ChestType.Savannah) { _price = savannahChestPrice; } // solium-disable-line whitespace else if (_chestType == ChestType.Forest ) { _price = forestChestPrice; } // solium-disable-line whitespace, lbrace else if (_chestType == ChestType.Arctic ) { _price = arcticChestPrice; } // solium-disable-line whitespace, lbrace else if (_chestType == ChestType.Mystic ) { _price = mysticChestPrice; } // solium-disable-line whitespace, lbrace else { revert(); } // solium-disable-line whitespace, lbrace _price = _price .mul(_getPresentPercentage()) .div(10000) .mul(_chestAmount); if (_tokenAddress == address(lunaContract)) { _price = _price .mul(uint256(10000).sub(cashbackPercentage)) .ceilingDiv(10000); } } function _getLunaCashbackAmount( uint256 _ethPrice, address _tokenAddress ) internal view returns (uint256 _lunaCashbackAmount) { if (_tokenAddress != address(lunaContract)) { (uint256 _lunaPrice, ) = _convertToken(ethAddress, _ethPrice, address(lunaContract)); return _lunaPrice .mul(cashbackPercentage) .div(uint256(10000)); } } function _getReferralPercentage(address _referrer, address _owner) internal view returns (uint256 _percentage) { return _referrer != _owner && _referrer != address(0) ? Math.max(referralPercentage[_referrer], defaultReferralPercentage) : 0; } function _purchase( ChestType _chestType, uint256 _chestAmount, address _tokenAddress, uint256 _maxTokenAmount, uint256 _minConversionRate, address payable _buyer, address _owner, address payable _referrer ) internal { require(_chestAmount <= chestCap[uint8(_chestType)]); require(_tokenAddress == ethAddress ? msg.value >= _maxTokenAmount : msg.value == 0); uint256 _totalPrice = _getEthPrice(_chestType, _chestAmount, _tokenAddress); uint256 _lunaCashbackAmount = _getLunaCashbackAmount(_totalPrice, _tokenAddress); uint256 _tokenAmount; uint256 _ethAmount; if (_tokenAddress != ethAddress) { (_tokenAmount, _ethAmount) = _swapToken( _tokenAddress, _maxTokenAmount, ethAddress, _totalPrice, _minConversionRate, _buyer, address(this) ); } else { // Check if the buyer allowed to spend that much ETH. require(_maxTokenAmount >= _totalPrice); // Require minimum conversion rate to be 0. require(_minConversionRate == 0); _tokenAmount = _totalPrice; _ethAmount = msg.value; } // Check if we received enough payment. require(_ethAmount >= _totalPrice); // Send back the ETH change, if there is any. if (_ethAmount > _totalPrice) { _buyer.transfer(_ethAmount - _totalPrice); } chestCap[uint8(_chestType)] -= _chestAmount; emit ChestPurchased( _chestType, _chestAmount, _tokenAddress, _tokenAmount, _totalPrice, _lunaCashbackAmount, _buyer, _owner ); if (_tokenAddress != address(lunaContract)) { // Send LUNA cashback. require(lunaContract.transferFrom(lunaBankAddress, _owner, _lunaCashbackAmount)); } if (!_hasCustomTokenRate(_tokenAddress)) { uint256 _referralReward = _totalPrice .mul(_getReferralPercentage(_referrer, _owner)) .div(10000); // If the referral reward cannot be sent because of a referrer's fault, set it to 0. // solium-disable-next-line security/no-send if (_referralReward > 0 && !_referrer.send(_referralReward)) { _referralReward = 0; } if (_referralReward > 0) { emit ReferralRewarded(_referrer, _referralReward); } } } }
solium-disable-line whitespace, lbrace
else if (_chestType == ChestType.Arctic ) { _price = arcticChestPrice; }
7,215,298
[ 1, 18281, 5077, 17, 8394, 17, 1369, 7983, 16, 7831, 9963, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 469, 309, 261, 67, 343, 395, 559, 422, 1680, 395, 559, 18, 686, 299, 335, 225, 262, 288, 389, 8694, 273, 25794, 335, 782, 395, 5147, 31, 282, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./interfaces/IDeFiatGov.sol"; import "./utils/DeFiatUtils.sol"; contract DeFiatGov is IDeFiatGov, DeFiatUtils { event RightsUpdated(address indexed caller, address indexed subject, uint256 level); event RightsRevoked(address indexed caller, address indexed subject); event MastermindUpdated(address indexed caller, address indexed subject); event FeeDestinationUpdated(address indexed caller, address feeDestination); event TxThresholdUpdated(address indexed caller, uint256 txThreshold); event BurnRateUpdated(address indexed caller, uint256 burnRate); event FeeRateUpdated(address indexed caller, uint256 feeRate); address public override mastermind; mapping (address => uint256) private actorLevel; // governance = multi-tier level address private feeDestination; // target address for fees uint256 private txThreshold; // min dft transferred to mint dftp uint256 private burnRate; // % burn on each tx, 10 = 1% uint256 private feeRate; // % fee on each tx, 10 = 1% modifier onlyMastermind { require(msg.sender == mastermind, "Gov: Only Mastermind"); _; } modifier onlyGovernor { require(actorLevel[msg.sender] >= 2,"Gov: Only Governors"); _; } modifier onlyPartner { require(actorLevel[msg.sender] >= 1,"Gov: Only Partners"); _; } constructor() public { mastermind = msg.sender; actorLevel[mastermind] = 3; feeDestination = mastermind; } // VIEW // Gov - Actor Level function viewActorLevelOf(address _address) public override view returns (uint256) { return actorLevel[_address]; } // Gov - Fee Destination / Treasury function viewFeeDestination() public override view returns (address) { return feeDestination; } // Points - Transaction Threshold function viewTxThreshold() public override view returns (uint256) { return txThreshold; } // Token - Burn Rate function viewBurnRate() public override view returns (uint256) { return burnRate; } // Token - Fee Rate function viewFeeRate() public override view returns (uint256) { return feeRate; } // Governed Functions // Update Actor Level, can only be performed with level strictly lower than msg.sender's level // Add/Remove user governance rights function setActorLevel(address user, uint256 level) public { require(level < actorLevel[msg.sender], "ActorLevel: Can only grant rights below you"); require(actorLevel[user] < actorLevel[msg.sender], "ActorLevel: Can only update users below you"); actorLevel[user] = level; // updates level -> adds or removes rights emit RightsUpdated(msg.sender, user, level); } // MasterMind - Revoke all rights function removeAllRights(address user) public onlyMastermind { require(user != mastermind, "Mastermind: Cannot revoke own rights"); actorLevel[user] = 0; emit RightsRevoked(msg.sender, user); } // Mastermind - Transfer ownership of Governance function setMastermind(address _mastermind) public onlyMastermind { require(_mastermind != mastermind, "Mastermind: Cannot call self"); mastermind = _mastermind; // Only one mastermind actorLevel[_mastermind] = 3; actorLevel[mastermind] = 2; // new level for previous mastermind emit MastermindUpdated(msg.sender, mastermind); } // Gov - Update the Fee Destination function setFeeDestination(address _feeDestination) public onlyGovernor { require(_feeDestination != feeDestination, "FeeDestination: No destination change"); feeDestination = _feeDestination; emit FeeDestinationUpdated(msg.sender, feeDestination); } // Points - Update the Tx Threshold function changeTxThreshold(uint _txThreshold) public onlyGovernor { require(_txThreshold != txThreshold, "TxThreshold: No threshold change"); txThreshold = _txThreshold; emit TxThresholdUpdated(msg.sender, txThreshold); } // Token - Update the Burn Rate function changeBurnRate(uint _burnRate) public onlyGovernor { require(_burnRate <= 200, "BurnRate: 20% limit"); burnRate = _burnRate; emit BurnRateUpdated(msg.sender, burnRate); } // Token - Update the Fee Rate function changeFeeRate(uint _feeRate) public onlyGovernor { require(_feeRate <= 200, "FeeRate: 20% limit"); feeRate = _feeRate; emit FeeRateUpdated(msg.sender, feeRate); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IDeFiatGov { function mastermind() external view returns (address); function viewActorLevelOf(address _address) external view returns (uint256); function viewFeeDestination() external view returns (address); function viewTxThreshold() external view returns (uint256); function viewBurnRate() external view returns (uint256); function viewFeeRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../lib/@openzeppelin/token/ERC20/IERC20.sol"; import "../lib/@openzeppelin/access/Ownable.sol"; abstract contract DeFiatUtils is Ownable { event TokenSweep(address indexed user, address indexed token, uint256 amount); // Sweep any tokens/ETH accidentally sent or airdropped to the contract function sweep(address token) external onlyOwner { uint256 amount = IERC20(token).balanceOf(address(this)); require(amount > 0, "Sweep: No token balance"); IERC20(token).transfer(msg.sender, amount); // use of the ERC20 traditional transfer if (address(this).balance > 0) { payable(msg.sender).transfer(address(this).balance); } emit TokenSweep(msg.sender, token, amount); } // Self-Destruct contract to free space on-chain, sweep any ETH to owner function kill() external onlyOwner { selfdestruct(payable(msg.sender)); } }
governance = multi-tier level
mapping (address => uint256) private actorLevel;
1,132,814
[ 1, 75, 1643, 82, 1359, 273, 3309, 17, 88, 2453, 1801, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 8327, 2355, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; // File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol /** * @title Block Relay Interface * @notice Interface of a Block Relay to a Witnet network * It defines how to interact with the Block Relay in order to support: * - Retrieve last beacon information * - Verify proof of inclusions (PoIs) of data request and tally transactions * @author Witnet Foundation */ interface BlockRelayInterface { /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory); /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view returns(uint256); /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view returns(uint256); /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies the validity of a tally PoI against the Tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid tally PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view returns(bool); /// @notice Verifies if the block relay can be upgraded /// @return true if contract is upgradable function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol /** * @title Block relay contract * @notice Contract to store/read block headers from the Witnet network * @author Witnet Foundation */ contract CentralizedBlockRelay is BlockRelayInterface { struct MerkleRoots { // hash of the merkle root of the DRs in Witnet uint256 drHashMerkleRoot; // hash of the merkle root of the tallies in Witnet uint256 tallyHashMerkleRoot; } struct Beacon { // hash of the last block uint256 blockHash; // epoch of the last block uint256 epoch; } // Address of the block pusher address public witnet; // Last block reported Beacon public lastBlock; mapping (uint256 => MerkleRoots) public blocks; // Event emitted when a new block is posted to the contract event NewBlock(address indexed _from, uint256 _id); // Only the owner should be able to push blocks modifier isOwner() { require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts. _; // Otherwise, it continues. } // Ensures block exists modifier blockExists(uint256 _id){ require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block"); _; } // Ensures block does not exist modifier blockDoesNotExist(uint256 _id){ require(blocks[_id].drHashMerkleRoot==0, "The block already existed"); _; } constructor() public{ // Only the contract deployer is able to push blocks witnet = msg.sender; } /// @dev Read the beacon of the last block inserted /// @return bytes to be signed by bridge nodes function getLastBeacon() external view override returns(bytes memory) { return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch); } /// @notice Returns the lastest epoch reported to the block relay. /// @return epoch function getLastEpoch() external view override returns(uint256) { return lastBlock.epoch; } /// @notice Returns the latest hash reported to the block relay /// @return blockhash function getLastHash() external view override returns(uint256) { return lastBlock.blockHash; } /// @dev Verifies the validity of a PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot; return(verifyPoi( _poi, drMerkleRoot, _index, _element)); } /// @dev Verifies the validity of a PoI against the tally merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _index the index in the merkle tree of the element to verify /// @param _element the element /// @return true or false depending the validity function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _index, uint256 _element) external view override blockExists(_blockHash) returns(bool) { uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot; return(verifyPoi( _poi, tallyMerkleRoot, _index, _element)); } /// @dev Verifies if the contract is upgradable /// @return true if the contract upgradable function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Post new block into the block relay /// @param _blockHash Hash of the block header /// @param _epoch Witnet epoch to which the block belongs to /// @param _drMerkleRoot Merkle root belonging to the data requests /// @param _tallyMerkleRoot Merkle root belonging to the tallies function postNewBlock( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot) external isOwner blockDoesNotExist(_blockHash) { lastBlock.blockHash = _blockHash; lastBlock.epoch = _epoch; blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot; blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot; emit NewBlock(witnet, _blockHash); } /// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header /// @return Requests-only merkle root hash in the block header. function readDrMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].drHashMerkleRoot; } /// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header. /// @param _blockHash Hash of the block header. /// @return tallies-only merkle root hash in the block header. function readTallyMerkleRoot(uint256 _blockHash) external view blockExists(_blockHash) returns(uint256) { return blocks[_blockHash].tallyHashMerkleRoot; } /// @dev Verifies the validity of a PoI /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _root the merkle root /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true or false depending the validity function verifyPoi( uint256[] memory _poi, uint256 _root, uint256 _index, uint256 _element) private pure returns(bool) { uint256 tree = _element; uint256 index = _index; // We want to prove that the hash of the _poi and the _element is equal to _root // For knowing if concatenate to the left or the right we check the parity of the the index for (uint i = 0; i < _poi.length; i++) { if (index%2 == 0) { tree = uint256(sha256(abi.encodePacked(tree, _poi[i]))); } else { tree = uint256(sha256(abi.encodePacked(_poi[i], tree))); } index = index >> 1; } return _root == tree; } } // File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay * @dev More information can be found here * DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks * @author Witnet Foundation */ contract BlockRelayProxy { // Address of the current controller address internal blockRelayAddress; // Current interface to the controller BlockRelayInterface internal blockRelayInstance; struct ControllerInfo { // last epoch seen by a controller uint256 lastEpoch; // address of the controller address blockRelayController; } // array containing the information about controllers ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use"); _; } constructor(address _blockRelayAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress})); blockRelayAddress = _blockRelayAddress; blockRelayInstance = BlockRelayInterface(_blockRelayAddress); } /// @notice Returns the beacon from the last inserted block. /// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility. /// @return last beacon in bytes function getLastBeacon() external view returns(bytes memory) { return blockRelayInstance.getLastBeacon(); } /// @notice Returns the last Wtinet epoch known to the block relay instance. /// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request. function getLastEpoch() external view returns(uint256) { return blockRelayInstance.getLastEpoch(); } /// @notice Verifies the validity of a data request PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyDrPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyDrPoi( _poi, _blockHash, _index, _element); } /// @notice Verifies the validity of a tally PoI against the DR merkle root /// @param _poi the proof of inclusion as [sibling1, sibling2,..] /// @param _blockHash the blockHash /// @param _epoch the epoch of the blockchash /// @param _index the index in the merkle tree of the element to verify /// @param _element the leaf to be verified /// @return true if valid data request PoI function verifyTallyPoi( uint256[] calldata _poi, uint256 _blockHash, uint256 _epoch, uint256 _index, uint256 _element) external view returns(bool) { address controller = getController(_epoch); return BlockRelayInterface(controller).verifyTallyPoi( _poi, _blockHash, _index, _element); } /// @notice Upgrades the block relay if the current one is upgradeable /// @param _newAddress address of the new block relay to upgrade function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) { // Check if the controller is upgradeable require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Get last epoch seen by the replaced controller uint256 epoch = blockRelayInstance.getLastEpoch(); // Get the length of last epochs seen by the different controllers uint256 n = controllers.length; // If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0 // just update the already anotated epoch with the new address, ignoring the previously inserted controller // Else, anotate the epoch from which the new controller should start receiving blocks if (epoch < controllers[n-1].lastEpoch) { controllers[n-1].blockRelayController = _newAddress; } else { controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress})); } // Update instance blockRelayAddress = _newAddress; blockRelayInstance = BlockRelayInterface(_newAddress); } /// @notice Gets the controller associated with the BR controller corresponding to the epoch provided /// @param _epoch the epoch to work with function getController(uint256 _epoch) public view returns(address _controller) { // Get length of all last epochs seen by controllers uint256 n = controllers.length; // Go backwards until we find the controller having that blockhash for (uint i = n; i > 0; i--) { if (_epoch >= controllers[i-1].lastEpoch) { return (controllers[i-1].blockRelayController); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: elliptic-curve-solidity/contracts/EllipticCurve.sol /** * @title Elliptic Curve Library * @dev Library providing arithmetic operations over elliptic curves. * @author Witnet Foundation */ library EllipticCurve { /// @dev Modular euclidean inverse of a number (mod p). /// @param _x The number /// @param _pp The modulus /// @return q such that x*q = 1 (mod _pp) function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) { require(_x != 0 && _x != _pp && _pp != 0, "Invalid number"); uint256 q = 0; uint256 newT = 1; uint256 r = _pp; uint256 newR = _x; uint256 t; while (newR != 0) { t = r / newR; (q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp)); (r, newR) = (newR, r - t * newR ); } return q; } /// @dev Modular exponentiation, b^e % _pp. /// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol /// @param _base base /// @param _exp exponent /// @param _pp modulus /// @return r such that r = b**e (mod _pp) function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) { require(_pp!=0, "Modulus is zero"); if (_base == 0) return 0; if (_exp == 0) return 1; uint256 r = 1; uint256 bit = 2 ** 255; assembly { for { } gt(bit, 0) { }{ r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp) r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp) bit := div(bit, 16) } } return r; } /// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1). /// @param _x coordinate x /// @param _y coordinate y /// @param _z coordinate z /// @param _pp the modulus /// @return (x', y') affine coordinates function toAffine( uint256 _x, uint256 _y, uint256 _z, uint256 _pp) internal pure returns (uint256, uint256) { uint256 zInv = invMod(_z, _pp); uint256 zInv2 = mulmod(zInv, zInv, _pp); uint256 x2 = mulmod(_x, zInv2, _pp); uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp); return (x2, y2); } /// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf). /// @param _prefix parity byte (0x02 even, 0x03 odd) /// @param _x coordinate x /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return y coordinate y function deriveY( uint8 _prefix, uint256 _x, uint256 _aa, uint256 _bb, uint256 _pp) internal pure returns (uint256) { require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix"); // x^3 + ax + b uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp); y2 = expMod(y2, (_pp + 1) / 4, _pp); // uint256 cmp = yBit ^ y_ & 1; uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2; return y; } /// @dev Check whether point (x,y) is on curve defined by a, b, and _pp. /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of curve /// @param _bb constant of curve /// @param _pp the modulus /// @return true if x,y in the curve, false else function isOnCurve( uint _x, uint _y, uint _aa, uint _bb, uint _pp) internal pure returns (bool) { if (0 == _x || _x == _pp || 0 == _y || _y == _pp) { return false; } // y^2 uint lhs = mulmod(_y, _y, _pp); // x^3 uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp); if (_aa != 0) { // x^3 + a*x rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp); } if (_bb != 0) { // x^3 + a*x + b rhs = addmod(rhs, _bb, _pp); } return lhs == rhs; } /// @dev Calculate inverse (x, -y) of point (x, y). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _pp the modulus /// @return (x, -y) function ecInv( uint256 _x, uint256 _y, uint256 _pp) internal pure returns (uint256, uint256) { return (_x, (_pp - _y) % _pp); } /// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1+P2 in affine coordinates function ecAdd( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { uint x = 0; uint y = 0; uint z = 0; // Double if x1==x2 else add if (_x1==_x2) { (x, y, z) = jacDouble( _x1, _y1, 1, _aa, _pp); } else { (x, y, z) = jacAdd( _x1, _y1, 1, _x2, _y2, 1, _pp); } // Get back to affine return toAffine( x, y, z, _pp); } /// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates. /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _x2 coordinate x of P2 /// @param _y2 coordinate y of P2 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = P1-P2 in affine coordinates function ecSub( uint256 _x1, uint256 _y1, uint256 _x2, uint256 _y2, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // invert square (uint256 x, uint256 y) = ecInv(_x2, _y2, _pp); // P1-square return ecAdd( _x1, _y1, x, y, _aa, _pp); } /// @dev Multiply point (x1, y1, z1) times d in affine coordinates. /// @param _k scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _aa constant of the curve /// @param _pp the modulus /// @return (qx, qy) = d*P in affine coordinates function ecMul( uint256 _k, uint256 _x, uint256 _y, uint256 _aa, uint256 _pp) internal pure returns(uint256, uint256) { // Jacobian multiplication (uint256 x1, uint256 y1, uint256 z1) = jacMul( _k, _x, _y, 1, _aa, _pp); // Get back to affine return toAffine( x1, y1, z1, _pp); } /// @dev Adds two points (x1, y1, z1) and (x2 y2, z2). /// @param _x1 coordinate x of P1 /// @param _y1 coordinate y of P1 /// @param _z1 coordinate z of P1 /// @param _x2 coordinate x of square /// @param _y2 coordinate y of square /// @param _z2 coordinate z of square /// @param _pp the modulus /// @return (qx, qy, qz) P1+square in Jacobian function jacAdd( uint256 _x1, uint256 _y1, uint256 _z1, uint256 _x2, uint256 _y2, uint256 _z2, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if ((_x1==0)&&(_y1==0)) return (_x2, _y2, _z2); if ((_x2==0)&&(_y2==0)) return (_x1, _y1, _z1); // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3 zs[0] = mulmod(_z1, _z1, _pp); zs[1] = mulmod(_z1, zs[0], _pp); zs[2] = mulmod(_z2, _z2, _pp); zs[3] = mulmod(_z2, zs[2], _pp); // u1, s1, u2, s2 zs = [ mulmod(_x1, zs[2], _pp), mulmod(_y1, zs[3], _pp), mulmod(_x2, zs[0], _pp), mulmod(_y2, zs[1], _pp) ]; // In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used require(zs[0] != zs[2], "Invalid data"); uint[4] memory hr; //h hr[0] = addmod(zs[2], _pp - zs[0], _pp); //r hr[1] = addmod(zs[3], _pp - zs[1], _pp); //h^2 hr[2] = mulmod(hr[0], hr[0], _pp); // h^3 hr[3] = mulmod(hr[2], hr[0], _pp); // qx = -h^3 -2u1h^2+r^2 uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp); qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp); // qy = -s1*z1*h^3+r(u1*h^2 -x^3) uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp); qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp); // qz = h*z1*z2 uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp); return(qx, qy, qz); } /// @dev Doubles a points (x, y, z). /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _pp the modulus /// @param _aa the a scalar in the curve equation /// @return (qx, qy, qz) 2P in Jacobian function jacDouble( uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { if (_z == 0) return (_x, _y, _z); uint256[3] memory square; // We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5 // Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4) square[0] = mulmod(_x, _x, _pp); //x1^2 square[1] = mulmod(_y, _y, _pp); //y1^2 square[2] = mulmod(_z, _z, _pp); //z1^2 // s uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp); // m uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp); // qx uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp); // qy = -8*y1^4 + M(S-T) uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp); // qz = 2*y1*z1 uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp); return (qx, qy, qz); } /// @dev Multiply point (x, y, z) times d. /// @param _d scalar to multiply /// @param _x coordinate x of P1 /// @param _y coordinate y of P1 /// @param _z coordinate z of P1 /// @param _aa constant of curve /// @param _pp the modulus /// @return (qx, qy, qz) d*P1 in Jacobian function jacMul( uint256 _d, uint256 _x, uint256 _y, uint256 _z, uint256 _aa, uint256 _pp) internal pure returns (uint256, uint256, uint256) { uint256 remaining = _d; uint256[3] memory point; point[0] = _x; point[1] = _y; point[2] = _z; uint256 qx = 0; uint256 qy = 0; uint256 qz = 1; if (_d == 0) { return (qx, qy, qz); } // Double and add algorithm while (remaining != 0) { if ((remaining & 1) != 0) { (qx, qy, qz) = jacAdd( qx, qy, qz, point[0], point[1], point[2], _pp); } remaining = remaining / 2; (point[0], point[1], point[2]) = jacDouble( point[0], point[1], point[2], _aa, _pp); } return (qx, qy, qz); } } // File: vrf-solidity/contracts/VRF.sol /** * @title Verifiable Random Functions (VRF) * @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function. * @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979). * It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve. * @author Witnet Foundation */ library VRF { /** * Secp256k1 parameters */ // Generator coordinate `x` of the EC curve uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; // Generator coordinate `y` of the EC curve uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; // Constant `a` of EC equation uint256 public constant AA = 0; // Constant `b` of EC equation uint256 public constant BB = 7; // Prime number of the curve uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // Order of the curve uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; /// @dev Public key derivation from private key. /// @param _d The scalar /// @param _x The coordinate x /// @param _y The coordinate y /// @return (qx, qy) The derived point function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) { return EllipticCurve.ecMul( _d, _x, _y, AA, PP ); } /// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`). /// @param _yByte The parity byte following the ec point compressed format /// @param _x The coordinate `x` of the point /// @return The coordinate `y` of the point function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) { return EllipticCurve.deriveY( _yByte, _x, AA, BB, PP); } /// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix /// concatenated with the gamma point /// @param _gammaX The x-coordinate of the gamma EC point /// @param _gammaY The y-coordinate of the gamma EC point /// @return The VRF hash ouput as shas256 digest function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) { bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(0xFE), // 0x01 uint8(0x03), // Compressed Gamma Point encodePoint(_gammaX, _gammaY)); return sha256(c); } /// @dev VRF verification by providing the public key, the message and the VRF proof. /// This function computes several elliptic curve operations which may lead to extensive gas consumption. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return true, if VRF proof is valid function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) { // Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3: U = s*B - c*Y (where B is the generator) (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Step 4: V = s*H - c*Gamma (uint256 vPointX, uint256 vPointY) = ecMulSubMul( _proof[3], hPoint[0], hPoint[1], _proof[2], _proof[0],_proof[1]); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], uPointX, uPointY, vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut. /// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes. /// 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 /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @param _uPoint The `u` EC point defined as `U = s*B - c*Y` /// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma` /// @return true, if VRF proof is valid function fastVerify( uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message, uint256[2] memory _uPoint, uint256[4] memory _vComponents) internal pure returns (bool) { // Step 2: Hash to try and increment -> hashed value, a finite EC point in G uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); // Step 3 & Step 4: // U = s*B - c*Y (where B is the generator) // V = s*H - c*Gamma if (!ecMulSubMulVerify( _proof[3], _proof[2], _publicKey[0], _publicKey[1], _uPoint[0], _uPoint[1]) || !ecMulVerify( _proof[3], hPoint[0], hPoint[1], _vComponents[0], _vComponents[1]) || !ecMulVerify( _proof[2], _proof[0], _proof[1], _vComponents[2], _vComponents[3]) ) { return false; } (uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub( _vComponents[0], _vComponents[1], _vComponents[2], _vComponents[3], AA, PP); // Step 5: derived c from hash points(...) bytes16 derivedC = hashPoints( hPoint[0], hPoint[1], _proof[0], _proof[1], _uPoint[0], _uPoint[1], vPointX, vPointY); // Step 6: Check validity c == c' return uint128(derivedC) == _proof[2]; } /// @dev Decode VRF proof from bytes /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) { require(_proof.length == 81, "Malformed VRF proof"); uint8 gammaSign; uint256 gammaX; uint128 c; uint256 s; assembly { gammaSign := mload(add(_proof, 1)) gammaX := mload(add(_proof, 33)) c := mload(add(_proof, 49)) s := mload(add(_proof, 81)) } uint256 gammaY = deriveY(gammaSign, gammaX); return [ gammaX, gammaY, c, s]; } /// @dev Decode EC point from bytes /// @param _point The EC point as bytes /// @return The point as `[point-x, point-y]` function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) { require(_point.length == 33, "Malformed compressed EC point"); uint8 sign; uint256 x; assembly { sign := mload(add(_point, 1)) x := mload(add(_point, 33)) } uint256 y = deriveY(sign, x); return [x, y]; } /// @dev Compute the parameters (EC points) required for the VRF fast verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]` /// @param _message The message (in bytes) used for computing the VRF /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])` function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (uint256[2] memory, uint256[4] memory) { // Requirements for Step 3: U = s*B - c*Y (where B is the generator) uint256[2] memory hPoint; (hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message); (uint256 uPointX, uint256 uPointY) = ecMulSubMul( _proof[3], GX, GY, _proof[2], _publicKey[0], _publicKey[1]); // Requirements for Step 4: V = s*H - c*Gamma (uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]); (uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]); return ( [uPointX, uPointY], [ sHX, sHY, cGammaX, cGammaY ]); } /// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 2 of VRF verification function. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]` /// @param _message The message used for computing the VRF /// @return The hash point in affine cooridnates function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) { // Step 1: public key to bytes // Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr bytes memory c = abi.encodePacked( // Cipher suite code (SECP256K1-SHA256-TAI is 0xFE) uint8(254), // 0x01 uint8(1), // Public Key encodePoint(_publicKey[0], _publicKey[1]), // Message _message); // Step 3: find a valid EC point // Loop over counter ctr starting at 0x00 and do hash for (uint8 ctr = 0; ctr < 256; ctr++) { // Counter update // c[cLength-1] = byte(ctr); bytes32 sha = sha256(abi.encodePacked(c, ctr)); // Step 4: arbitraty string to point and check if it is on curve uint hPointX = uint256(sha); uint hPointY = deriveY(2, hPointX); if (EllipticCurve.isOnCurve( hPointX, hPointY, AA, BB, PP)) { // Step 5 (omitted): calculate H (cofactor is 1 on secp256k1) // If H is not "INVALID" and cofactor > 1, set H = cofactor * H return (hPointX, hPointY); } } revert("No valid point was found"); } /// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04). /// Used in Step 5 of VRF verification function. /// @param _hPointX The coordinate `x` of point `H` /// @param _hPointY The coordinate `y` of point `H` /// @param _gammaX The coordinate `x` of the point `Gamma` /// @param _gammaX The coordinate `y` of the point `Gamma` /// @param _uPointX The coordinate `x` of point `U` /// @param _uPointY The coordinate `y` of point `U` /// @param _vPointX The coordinate `x` of point `V` /// @param _vPointY The coordinate `y` of point `V` /// @return The first half of the digest of the points using SHA256 function hashPoints( uint256 _hPointX, uint256 _hPointY, uint256 _gammaX, uint256 _gammaY, uint256 _uPointX, uint256 _uPointY, uint256 _vPointX, uint256 _vPointY) internal pure returns (bytes16) { bytes memory c = abi.encodePacked( // Ciphersuite 0xFE uint8(254), // Prefix 0x02 uint8(2), // Points to Bytes encodePoint(_hPointX, _hPointY), encodePoint(_gammaX, _gammaY), encodePoint(_uPointX, _uPointY), encodePoint(_vPointX, _vPointY) ); // Hash bytes and truncate bytes32 sha = sha256(c); bytes16 half1; assembly { let freemem_pointer := mload(0x40) mstore(add(freemem_pointer,0x00), sha) half1 := mload(add(freemem_pointer,0x00)) } return half1; } /// @dev Encode an EC point to bytes /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The point coordinates as bytes function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) { uint8 prefix = uint8(2 + (_y % 2)); return abi.encodePacked(prefix, _x); } /// @dev Substracts two key derivation functionsas `s1*A - s2*B`. /// @param _scalar1 The scalar `s1` /// @param _a1 The `x` coordinate of point `A` /// @param _a2 The `y` coordinate of point `A` /// @param _scalar2 The scalar `s2` /// @param _b1 The `x` coordinate of point `B` /// @param _b2 The `y` coordinate of point `B` /// @return The derived point in affine cooridnates function ecMulSubMul( uint256 _scalar1, uint256 _a1, uint256 _a2, uint256 _scalar2, uint256 _b1, uint256 _b2) internal pure returns (uint256, uint256) { (uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2); (uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2); (uint256 r1, uint256 r2) = EllipticCurve.ecSub( m1, m2, n1, n2, AA, PP); return (r1, r2); } /// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// 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 /// @param _scalar The scalar of the point multiplication /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @param _qx The coordinate `x` of the multiplication result /// @param _qy The coordinate `y` of the multiplication result /// @return true, if first 20 bytes match function ecMulVerify( uint256 _scalar, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { address result = ecrecover( 0, _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(_scalar, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC. /// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes. /// Based on SolCrypto library: https://github.com/HarryR/solcrypto /// @param _scalar1 The scalar of the multiplication of `(gx,gy)` /// @param _scalar2 The scalar of the multiplication of `(x,y)` /// @param _x The coordinate `x` of the point to be mutiply by `scalar2` /// @param _y The coordinate `y` of the point to be mutiply by `scalar2` /// @param _qx The coordinate `x` of the equation result /// @param _qy The coordinate `y` of the equation result /// @return true, if first 20 bytes match function ecMulSubMulVerify( uint256 _scalar1, uint256 _scalar2, uint256 _x, uint256 _y, uint256 _qx, uint256 _qy) internal pure returns(bool) { uint256 scalar1 = (NN - _scalar1) % NN; scalar1 = mulmod(scalar1, _x, NN); uint256 scalar2 = (NN - _scalar2) % NN; address result = ecrecover( bytes32(scalar1), _y % 2 != 0 ? 28 : 27, bytes32(_x), bytes32(mulmod(scalar2, _x, NN))); return pointToAddress(_qx, _qy) == result; } /// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest. /// This function is used for performing a fast EC multiplication verification. /// @param _x The coordinate `x` of the point /// @param _y The coordinate `y` of the point /// @return The address of the EC point digest (keccak256) function pointToAddress(uint256 _x, uint256 _y) internal pure returns(address) { return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } } // File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol /** * @title Active Bridge Set (ABS) library * @notice This library counts the number of bridges that were active recently. */ library ActiveBridgeSetLib { // Number of Ethereum blocks during which identities can be pushed into a single activity slot uint8 public constant CLAIM_BLOCK_PERIOD = 8; // Number of activity slots in the ABS uint8 public constant ACTIVITY_LENGTH = 100; struct ActiveBridgeSet { // Mapping of activity slots with participating identities mapping (uint16 => address[]) epochIdentities; // Mapping of identities with their participation count mapping (address => uint16) identityCount; // Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`) uint32 activeIdentities; // Number of identities for the next activity slot (to be updated in the next activity slot) uint32 nextActiveIdentities; // Last used block number during an activity update uint256 lastBlockNumber; } modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) { require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block"); _; } /// @dev Updates activity in Witnet without requiring protocol participation. /// @param _abs The Active Bridge Set structure to be updated. /// @param _blockNumber The block number up to which the activity should be updated. function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Avoid gas cost if ABS is up to date require( updateABS( _abs, currentSlot, lastSlot, overflow ), "The ABS was already up to date"); _abs.lastBlockNumber = _blockNumber; } /// @dev Pushes activity updates through protocol activities (implying insertion of identity). /// @param _abs The Active Bridge Set structure to be updated. /// @param _address The address pushing the activity. /// @param _blockNumber The block number up to which the activity should be updated. function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber) internal validBlockNumber(_blockNumber, _abs.lastBlockNumber) returns (bool success) { (uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber); // Update ABS and if it was already up to date, check if identities already counted if ( updateABS( _abs, currentSlot, lastSlot, overflow )) { _abs.lastBlockNumber = _blockNumber; } else { // Check if address was already counted as active identity in this current activity slot uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length; for (uint256 i; i < epochIdsLength; i++) { if (_abs.epochIdentities[currentSlot][i] == _address) { return false; } } } // Update current activity slot with identity: // 1. Add currentSlot to `epochIdentities` with address // 2. If count = 0, increment by 1 `nextActiveIdentities` // 3. Increment by 1 the count of the identity _abs.epochIdentities[currentSlot].push(_address); if (_abs.identityCount[_address] == 0) { _abs.nextActiveIdentities++; } _abs.identityCount[_address]++; return true; } /// @dev Checks if an address is a member of the ABS. /// @param _abs The Active Bridge Set structure from the Witnet Requests Board. /// @param _address The address to check. /// @return true if address is member of ABS. function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) { return _abs.identityCount[_address] > 0; } /// @dev Gets the slots of the last block seen by the ABS provided and the block number provided. /// @param _abs The Active Bridge Set structure containing the last block. /// @param _blockNumber The block number from which to get the current slot. /// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference &gt; CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH. function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) { // Get current activity slot number uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Get last actitivy slot number uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH); // Check if there was an activity slot overflow // `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH); return (currentSlot, lastSlot, overflow); } /// @dev Updates the provided ABS according to the slots provided. /// @param _abs The Active Bridge Set to be updated. /// @param _currentSlot The current slot. /// @param _lastSlot The last slot seen by the ABS. /// @param _overflow Whether the current slot has overflown the last slot. /// @return True if update occurred. function updateABS( ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot, bool _overflow) private returns (bool) { // If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS if (_overflow) { flushABS(_abs, _lastSlot, _lastSlot); // If ABS are not up to date => fill previous activity slots with empty activities } else if (_currentSlot != _lastSlot) { flushABS(_abs, _currentSlot, _lastSlot); } else { return false; } return true; } /// @dev Flushes the provided ABS record between lastSlot and currentSlot. /// @param _abs The Active Bridge Set to be flushed. /// @param _currentSlot The current slot. function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private { // For each slot elapsed, remove identities and update `nextActiveIdentities` count for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) { flushSlot(_abs, slot); } // Update current activity slot flushSlot(_abs, _currentSlot); _abs.activeIdentities = _abs.nextActiveIdentities; } /// @dev Flushes a slot of the provided ABS. /// @param _abs The Active Bridge Set to be flushed. /// @param _slot The slot to be flushed. function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private { // For a given slot, go through all identities to flush them uint256 epochIdsLength = _abs.epochIdentities[_slot].length; for (uint256 id = 0; id < epochIdsLength; id++) { flushIdentity(_abs, _abs.epochIdentities[_slot][id]); } delete _abs.epochIdentities[_slot]; } /// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed. /// @param _abs The Active Bridge Set to be flushed. /// @param _address The address to be flushed. function flushIdentity(ActiveBridgeSet storage _abs, address _address) private { require(absMembership(_abs, _address), "The identity address is already out of the ARS"); // Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count _abs.identityCount[_address]--; if (_abs.identityCount[_address] == 0) { delete _abs.identityCount[_address]; _abs.nextActiveIdentities--; } } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol /** * @title Witnet Requests Board Interface * @notice Interface of a Witnet Request Board (WRB) * It defines how to interact with the WRB in order to support: * - Post and upgrade a data request * - Read the result of a dr * @author Witnet Foundation */ interface WitnetRequestsBoardInterface { /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256); /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable; /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR function readDrHash (uint256 _id) external view returns(uint256); /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult (uint256 _id) external view returns(bytes memory); /// @notice Verifies if the block relay can be upgraded. /// @return true if contract is upgradable. function isUpgradable(address _address) external view returns(bool); } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol /** * @title Witnet Requests Board * @notice Contract to bridge requests to Witnet. * @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network. * The result of the requests will be posted back to this contract by the bridge nodes too. * @author Witnet Foundation */ contract WitnetRequestsBoard is WitnetRequestsBoardInterface { using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet; // Expiration period after which a Witnet Request can be claimed again uint256 public constant CLAIM_EXPIRATION = 13; struct DataRequest { bytes dr; uint256 inclusionReward; uint256 tallyReward; bytes result; // Block number at which the DR was claimed for the last time uint256 blockNumber; uint256 drHash; address payable pkhClaim; } // Owner of the Witnet Request Board address public witnet; // Block Relay proxy prividing verification functions BlockRelayProxy public blockRelay; // Witnet Requests within the board DataRequest[] public requests; // Set of recently active bridges ActiveBridgeSetLib.ActiveBridgeSet public abs; // Replication factor for Active Bridge Set identities uint8 public repFactor; // Event emitted when a new DR is posted event PostedRequest(address indexed _from, uint256 _id); // Event emitted when a DR inclusion proof is posted event IncludedRequest(address indexed _from, uint256 _id); // Event emitted when a result proof is posted event PostedResult(address indexed _from, uint256 _id); // Ensures the reward is not greater than the value modifier payingEnough(uint256 _value, uint256 _tally) { require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward"); _; } // Ensures the poe is valid modifier poeValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) { require( verifyPoe( _poe, _publicKey, _uPoint, _vPointHelpers), "Not a valid PoE"); _; } // Ensures signature (sign(msg.sender)) is valid modifier validSignature( uint256[2] memory _publicKey, bytes memory addrSignature) { require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature"); _; } // Ensures the DR inclusion proof has not been reported yet modifier drNotIncluded(uint256 _id) { require(requests[_id].drHash == 0, "DR already included"); _; } // Ensures the DR inclusion has been already reported modifier drIncluded(uint256 _id) { require(requests[_id].drHash != 0, "DR not yet included"); _; } // Ensures the result has not been reported yet modifier resultNotIncluded(uint256 _id) { require(requests[_id].result.length == 0, "Result already included"); _; } // Ensures the VRF is valid modifier vrfValid( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) virtual { require( VRF.fastVerify( _publicKey, _poe, getLastBeacon(), _uPoint, _vPointHelpers), "Not a valid VRF"); _; } // Ensures the address belongs to the active bridge set modifier absMember(address _address) { require(abs.absMembership(_address), "Not a member of the ABS"); _; } /** * @notice Include an address to specify the Witnet Block Relay and a replication factor. * @param _blockRelayAddress BlockRelayProxy address. * @param _repFactor replication factor. */ constructor(address _blockRelayAddress, uint8 _repFactor) public { blockRelay = BlockRelayProxy(_blockRelayAddress); witnet = msg.sender; // Insert an empty request so as to initialize the requests array with length > 0 DataRequest memory request; requests.push(request); repFactor = _repFactor; } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _serialized, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) override returns(uint256) { // The initial length of the `requests` array will become the ID of the request for everything related to the WRB uint256 id = requests.length; // Create a new `DataRequest` object and initialize all the non-default fields DataRequest memory request; request.dr = _serialized; request.inclusionReward = SafeMath.sub(msg.value, _tallyReward); request.tallyReward = _tallyReward; // Push the new request into the contract state requests.push(request); // Let observers know that a new request has been posted emit PostedRequest(msg.sender, id); return id; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) resultNotIncluded(_id) override { if (requests[_id].drHash != 0) { require( msg.value == _tallyReward, "Txn value should equal result reward argument (request reward already paid)" ); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } else { requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward); requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward); } } /// @dev Checks if the data requests from a list are claimable or not. /// @param _ids The list of data request identifiers to be checked. /// @return An array of booleans indicating if data requests are claimable or not. function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) { uint256 idsLength = _ids.length; bool[] memory validIds = new bool[](idsLength); for (uint i = 0; i < idsLength; i++) { uint256 index = _ids[i]; validIds[i] = (dataRequestCanBeClaimed(requests[index])) && requests[index].drHash == 0 && index < requests.length && requests[index].result.length == 0; } return validIds; } /// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash). /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet. /// @param _index The index in the merkle tree. /// @param _blockHash The hash of the block in which the data request was inserted. /// @param _epoch The epoch in which the blockHash was created. function reportDataRequestInclusion( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch) external drNotIncluded(_id) { // Check the data request has been claimed require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed"); uint256 drOutputHash = uint256(sha256(requests[_id].dr)); uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0]))); // Update the state upon which this function depends before the external call requests[_id].drHash = drHash; require( blockRelay.verifyDrPoi( _poi, _blockHash, _epoch, _index, drOutputHash), "Invalid PoI"); requests[_id].pkhClaim.transfer(requests[_id].inclusionReward); // Push requests[_id].pkhClaim to abs abs.pushActivity(requests[_id].pkhClaim, block.number); emit IncludedRequest(msg.sender, _id); } /// @dev Reports the result of a data request in Witnet. /// @param _id The unique identifier of the data request. /// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block. /// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block. /// @param _blockHash The hash of the block in which the result (tally) was inserted. /// @param _epoch The epoch in which the blockHash was created. /// @param _result The result itself as bytes. function reportResult( uint256 _id, uint256[] calldata _poi, uint256 _index, uint256 _blockHash, uint256 _epoch, bytes calldata _result) external drIncluded(_id) resultNotIncluded(_id) absMember(msg.sender) { // Ensures the result byes do not have zero length // This would not be a valid encoding with CBOR and could trigger a reentrancy attack require(_result.length != 0, "Result has zero length"); // Update the state upon which this function depends before the external call requests[_id].result = _result; uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result))); require( blockRelay.verifyTallyPoi( _poi, _blockHash, _epoch, _index, resHash), "Invalid PoI"); msg.sender.transfer(requests[_id].tallyReward); emit PostedResult(msg.sender, _id); } /// @dev Retrieves the bytes of the serialization of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the data request as bytes. function readDataRequest(uint256 _id) external view returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].dr; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR function readResult(uint256 _id) external view override returns(bytes memory) { require(requests.length > _id, "Id not found"); return requests[_id].result; } /// @dev Retrieves hash of the data request transaction in Witnet. /// @param _id The unique identifier of the data request. /// @return The hash of the DataRequest transaction in Witnet. function readDrHash(uint256 _id) external view override returns(uint256) { require(requests.length > _id, "Id not found"); return requests[_id].drHash; } /// @dev Returns the number of data requests in the WRB. /// @return the number of data requests in the WRB. function requestsCount() external view returns(uint256) { return requests.length; } /// @notice Wrapper around the decodeProof from VRF library. /// @dev Decode VRF proof from bytes. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) { return VRF.decodeProof(_proof); } /// @notice Wrapper around the decodePoint from VRF library. /// @dev Decode EC point from bytes. /// @param _point The EC point as bytes. /// @return The point as `[point-x, point-y]`. function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) { return VRF.decodePoint(_point); } /// @dev Wrapper around the computeFastVerifyParams from VRF library. /// @dev Compute the parameters (EC points) required for the VRF fast verification function.. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`. /// @param _message The message (in bytes) used for computing the VRF. /// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`. function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message) external pure returns (uint256[2] memory, uint256[4] memory) { return VRF.computeFastVerifyParams(_publicKey, _proof, _message); } /// @dev Updates the ABS activity with the block number provided. /// @param _blockNumber update the ABS until this block number. function updateAbsActivity(uint256 _blockNumber) external { require (_blockNumber <= block.number, "The provided block number has not been reached"); abs.updateActivity(_blockNumber); } /// @dev Verifies if the contract is upgradable. /// @return true if the contract upgradable. function isUpgradable(address _address) external view override returns(bool) { if (_address == witnet) { return true; } return false; } /// @dev Claim drs to be posted to Witnet by the node. /// @param _ids Data request ids to be claimed. /// @param _poe PoE claiming eligibility. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function claimDataRequests( uint256[] memory _ids, uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers, bytes memory addrSignature) public validSignature(_publicKey, addrSignature) poeValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { for (uint i = 0; i < _ids.length; i++) { require( dataRequestCanBeClaimed(requests[_ids[i]]), "One of the listed data requests was already claimed" ); requests[_ids[i]].pkhClaim = msg.sender; requests[_ids[i]].blockNumber = block.number; } return true; } /// @dev Read the beacon of the last block inserted. /// @return bytes to be signed by the node as PoE. function getLastBeacon() public view virtual returns(bytes memory) { return blockRelay.getLastBeacon(); } /// @dev Claim drs to be posted to Witnet by the node. /// @param _poe PoE claiming eligibility. /// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`. /// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y. /// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma. function verifyPoe( uint256[4] memory _poe, uint256[2] memory _publicKey, uint256[2] memory _uPoint, uint256[4] memory _vPointHelpers) internal view vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers) returns(bool) { uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1])); // True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities if (abs.activeIdentities < repFactor) { return true; } // We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) { return true; } return false; } /// @dev Verifies the validity of a signature. /// @param _message message to be verified. /// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`. /// @param _addrSignature the signature to verify asas r||s||v. /// @return true or false depending the validity. function verifySig( bytes memory _message, uint256[2] memory _publicKey, bytes memory _addrSignature) internal pure returns(bool) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_addrSignature, 0x20)) s := mload(add(_addrSignature, 0x40)) v := byte(0, mload(add(_addrSignature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (v != 0 && v != 1) { return false; } v = 28 - v; bytes32 msgHash = sha256(_message); address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]); return ecrecover( msgHash, v, r, s) == hashedKey; } function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) { return (_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) && _request.drHash == 0 && _request.result.length == 0; } } // File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol /** * @title Block Relay Proxy * @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay. * @author Witnet Foundation */ contract WitnetRequestsBoardProxy { // Address of the Witnet Request Board contract that is currently being used address public witnetRequestsBoardAddress; // Struct if the information of each controller struct ControllerInfo { // Address of the Controller address controllerAddress; // The lastId of the previous Controller uint256 lastId; } // Last id of the WRB controller uint256 internal currentLastId; // Instance of the current WitnetRequestBoard WitnetRequestsBoardInterface internal witnetRequestsBoardInstance; // Array with the controllers that have been used in the Proxy ControllerInfo[] internal controllers; modifier notIdentical(address _newAddress) { require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use"); _; } /** * @notice Include an address to specify the Witnet Request Board. * @param _witnetRequestsBoardAddress WitnetRequestBoard address. */ constructor(address _witnetRequestsBoardAddress) public { // Initialize the first epoch pointing to the first controller controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0})); witnetRequestsBoardAddress = _witnetRequestsBoardAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress); } /// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. /// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output. /// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. /// @return The unique identifier of the data request. function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) { uint256 n = controllers.length; uint256 offset = controllers[n - 1].lastId; // Update the currentLastId with the id in the controller plus the offSet currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset; return currentLastId; } /// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward. /// @param _id The unique identifier of the data request. /// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward. function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable { address wrbAddress; uint256 wrbOffset; (wrbAddress, wrbOffset) = getController(_id); return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward); } /// @dev Retrieves the DR hash of the id from the WRB. /// @param _id The unique identifier of the data request. /// @return The hash of the DR. function readDrHash (uint256 _id) external view returns(uint256) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offsetWrb; (wrbAddress, offsetWrb) = getController(_id); // Return the result of the DR readed in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithDrHash; wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress); uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb); return drHash; } /// @dev Retrieves the result (if already available) of one data request from the WRB. /// @param _id The unique identifier of the data request. /// @return The result of the DR. function readResult(uint256 _id) external view returns(bytes memory) { // Get the address and the offset of the corresponding to id address wrbAddress; uint256 offSetWrb; (wrbAddress, offSetWrb) = getController(_id); // Return the result of the DR in the corresponding Controller with its own id WitnetRequestsBoardInterface wrbWithResult; wrbWithResult = WitnetRequestsBoardInterface(wrbAddress); return wrbWithResult.readResult(_id - offSetWrb); } /// @notice Upgrades the Witnet Requests Board if the current one is upgradeable. /// @param _newAddress address of the new block relay to upgrade. function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) { // Require the WRB is upgradable require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation"); // Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId})); // Upgrade the WRB witnetRequestsBoardAddress = _newAddress; witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress); } /// @notice Gets the controller from an Id. /// @param _id id of a Data Request from which we get the controller. function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) { // Check id is bigger than 0 require(_id > 0, "Non-existent controller for id 0"); uint256 n = controllers.length; // If the id is bigger than the lastId of a Controller, read the result in that Controller for (uint i = n; i > 0; i--) { if (_id > controllers[i - 1].lastId) { return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId); } } } } // File: witnet-ethereum-bridge/contracts/BufferLib.sol /** * @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface * @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will * start with the byte that goes right after the last one in the previous read. * @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some * theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded. */ library BufferLib { struct Buffer { bytes data; uint32 cursor; } // Ensures we access an existing index in an array modifier notOutOfBounds(uint32 index, uint256 length) { require(index < length, "Tried to read from a consumed Buffer (must rewind it first)"); _; } /** * @notice Read and consume a certain amount of bytes from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @param _length How many bytes to read and consume from the buffer. * @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position. */ function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) { // Make sure not to read out of the bounds of the original bytes require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading"); // Create a new `bytes memory destination` value bytes memory destination = new bytes(_length); bytes memory source = _buffer.data; uint32 offset = _buffer.cursor; // Get raw pointers for source and destination uint sourcePointer; uint destinationPointer; assembly { sourcePointer := add(add(source, 32), offset) destinationPointer := add(destination, 32) } // Copy `_length` bytes from source to destination memcpy(destinationPointer, sourcePointer, uint(_length)); // Move the cursor forward by `_length` bytes seek(_buffer, _length, true); return destination; } /** * @notice Read and consume the next byte from the buffer. * @param _buffer An instance of `BufferLib.Buffer`. * @return The next byte in the buffer counting from the cursor position. */ function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) { // Return the byte at the position marked by the cursor and advance the cursor all at once return _buffer.data[_buffer.cursor++]; } /** * @notice Move the inner cursor of the buffer to a relative or absolute position. * @param _buffer An instance of `BufferLib.Buffer`. * @param _offset How many bytes to move the cursor forward. * @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the * buffer (`true`). * @return The final position of the cursor (will equal `_offset` if `_relative` is `false`). */ // solium-disable-next-line security/no-assign-params function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) { // Deal with relative offsets if (_relative) { require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking"); _offset += _buffer.cursor; } // Make sure not to read out of the bounds of the original bytes require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking"); _buffer.cursor = _offset; return _buffer.cursor; } /** * @notice Move the inner cursor a number of bytes forward. * @dev This is a simple wrapper around the relative offset case of `seek()`. * @param _buffer An instance of `BufferLib.Buffer`. * @param _relativeOffset How many bytes to move the cursor forward. * @return The final position of the cursor. */ function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) { return seek(_buffer, _relativeOffset, true); } /** * @notice Move the inner cursor back to the first byte in the buffer. * @param _buffer An instance of `BufferLib.Buffer`. */ function rewind(Buffer memory _buffer) internal pure { _buffer.cursor = 0; } /** * @notice Read and consume the next byte from the buffer as an `uint8`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint8` value of the next byte in the buffer counting from the cursor position. */ function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint8 value; assembly { value := mload(add(add(bytesValue, 1), offset)) } _buffer.cursor++; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an `uint16`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position. */ function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint16 value; assembly { value := mload(add(add(bytesValue, 2), offset)) } _buffer.cursor += 2; return value; } /** * @notice Read and consume the next 4 bytes from the buffer as an `uint32`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint32 value; assembly { value := mload(add(add(bytesValue, 4), offset)) } _buffer.cursor += 4; return value; } /** * @notice Read and consume the next 8 bytes from the buffer as an `uint64`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position. */ function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint64 value; assembly { value := mload(add(add(bytesValue, 8), offset)) } _buffer.cursor += 8; return value; } /** * @notice Read and consume the next 16 bytes from the buffer as an `uint128`. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. */ function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint128 value; assembly { value := mload(add(add(bytesValue, 16), offset)) } _buffer.cursor += 16; return value; } /** * @notice Read and consume the next 32 bytes from the buffer as an `uint256`. * @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position. * @param _buffer An instance of `BufferLib.Buffer`. */ function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) { bytes memory bytesValue = _buffer.data; uint32 offset = _buffer.cursor; uint256 value; assembly { value := mload(add(add(bytesValue, 32), offset)) } _buffer.cursor += 32; return value; } /** * @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an * `int32`. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16` * use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are * expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard. * @param _buffer An instance of `BufferLib.Buffer`. * @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position. */ function readFloat16(Buffer memory _buffer) internal pure returns (int32) { uint32 bytesValue = readUint16(_buffer); // Get bit at position 0 uint32 sign = bytesValue & 0x8000; // Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15; // Get bits 6 to 15 int32 significand = int32(bytesValue & 0x03ff); // Add 1024 to the fraction if the exponent is 0 if (exponent == 15) { significand |= 0x400; } // Compute `2 ^ exponent · (1 + fraction / 1024)` int32 result = 0; if (exponent >= 0) { result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10); } else { result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10); } // Make the result negative if the sign bit is not 0 if (sign != 0) { result *= - 1; } return result; } /** * @notice Copy bytes from one memory address into another. * @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms * of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE). * @param _dest Address of the destination memory. * @param _src Address to the source memory. * @param _len How many bytes to copy. */ // solium-disable-next-line security/no-assign-params function memcpy(uint _dest, uint _src, uint _len) private pure { // 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)) } } } // File: witnet-ethereum-bridge/contracts/CBOR.sol /** * @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation” * @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize * the gas cost of decoding them into a useful native type. * @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js * TODO: add support for Array (majorType = 4) * TODO: add support for Map (majorType = 5) * TODO: add support for Float32 (majorType = 7, additionalInformation = 26) * TODO: add support for Float64 (majorType = 7, additionalInformation = 27) */ library CBOR { using BufferLib for BufferLib.Buffer; uint64 constant internal UINT64_MAX = ~uint64(0); struct Value { BufferLib.Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /** * @notice Decode a `CBOR.Value` structure into a native `bytes` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `bytes` value. */ function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory bytesData; // These checks look repetitive but the equivalent loop would be more expensive. uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType)); if (itemLength < UINT64_MAX) { bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength)); } } return bytesData; } else { return _cborValue.buffer.read(uint32(_cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a `fixed16` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16` * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeFixed16(Value memory _cborValue) public pure returns(int32) { require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7"); require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25"); return _cborValue.buffer.readFloat16(); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention. * as explained in `decodeFixed16`. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeFixed16(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `int128` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128` value. */ function decodeInt128(Value memory _cborValue) public pure returns(int128) { if (_cborValue.majorType == 1) { uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); return int128(-1) - int128(length); } else if (_cborValue.majorType == 0) { // Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer // a uniform API for positive and negative numbers return int128(decodeUint64(_cborValue)); } revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1"); } /** * @notice Decode a `CBOR.Value` structure into a native `int128[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `int128[]` value. */ function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) { require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `string` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as a `string` value. */ function decodeString(Value memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } } /** * @notice Decode a `CBOR.Value` structure into a native `string[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `string[]` value. */ function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) { require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); string[] memory array = new string[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeString(item); } return array; } /** * @notice Decode a `CBOR.Value` structure into a native `uint64` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64` value. */ function decodeUint64(Value memory _cborValue) public pure returns(uint64) { require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0"); return readLength(_cborValue.buffer, _cborValue.additionalInformation); } /** * @notice Decode a `CBOR.Value` structure into a native `uint64[]` value. * @param _cborValue An instance of `CBOR.Value`. * @return The value represented by the input, as an `uint64[]` value. */ function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) { require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported"); uint64[] memory array = new uint64[](length); for (uint64 i = 0; i < length; i++) { Value memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeUint64(item); } return array; } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) { BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0); return valueFromBuffer(buffer); } /** * @notice Decode a CBOR.Value structure from raw bytes. * @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types. * @param _buffer A Buffer structure representing a CBOR-encoded value. * @return A `CBOR.Value` instance containing a partially decoded value. */ function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) { require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value"); uint8 initialByte; uint8 majorType = 255; uint8 additionalInformation; uint64 length; uint64 tag = UINT64_MAX; bool isTagged = true; while (isTagged) { // Extract basic CBOR properties from input bytes initialByte = _buffer.readUint8(); majorType = initialByte >> 5; additionalInformation = initialByte & 0x1f; // Early CBOR tag parsing. if (majorType == 6) { tag = readLength(_buffer, additionalInformation); } else { isTagged = false; } } require(majorType <= 7, "Invalid CBOR major type"); return CBOR.Value( _buffer, initialByte, majorType, additionalInformation, length, tag); } // Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the // value of the `additionalInformation` argument. function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) { if (additionalInformation < 24) { return additionalInformation; } if (additionalInformation == 24) { return _buffer.readUint8(); } if (additionalInformation == 25) { return _buffer.readUint16(); } if (additionalInformation == 26) { return _buffer.readUint32(); } if (additionalInformation == 27) { return _buffer.readUint64(); } if (additionalInformation == 31) { return UINT64_MAX; } revert("Invalid length encoding (non-existent additionalInformation value)"); } // Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming // as many bytes as specified by the first byte. function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) { uint8 initialByte = _buffer.readUint8(); if (initialByte == 0xff) { return UINT64_MAX; } uint64 length = readLength(_buffer, initialByte & 0x1f); require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length"); return length; } // Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness, // but it can be easily casted into a string with `string(result)`. // solium-disable-next-line security/no-assign-params function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) { bytes memory result; for (uint64 index = 0; index < _length; index++) { uint8 value = _buffer.readUint8(); if (value & 0x80 != 0) { if (value < 0xe0) { value = (value & 0x1f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 1; } else if (value < 0xf0) { value = (value & 0x0f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 2; } else { value = (value & 0x0f) << 18 | (_buffer.readUint8() & 0x3f) << 12 | (_buffer.readUint8() & 0x3f) << 6 | (_buffer.readUint8() & 0x3f); _length -= 3; } } result = abi.encodePacked(result, value); } return result; } } // File: witnet-ethereum-bridge/contracts/Witnet.sol /** * @title A library for decoding Witnet request results * @notice The library exposes functions to check the Witnet request success. * and retrieve Witnet results from CBOR values into solidity types. */ library Witnet { using CBOR for CBOR.Value; /* STRUCTS */ struct Result { bool success; CBOR.Value cborValue; } /* ENUMS */ enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid RADON script. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, Size } /* Result impl's */ /** * @notice Decode raw CBOR bytes into a Result instance. * @param _cborBytes Raw bytes representing a CBOR-encoded value. * @return A `Result` instance. */ function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) { CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes); return resultFromCborValue(cborValue); } /** * @notice Decode a CBOR value into a Result instance. * @param _cborValue An instance of `CBOR.Value`. * @return A `Result` instance. */ function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) { // Witnet uses CBOR tag 39 to represent RADON error code identifiers. // [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md bool success = _cborValue.tag != 39; return Result(success, _cborValue); } /** * @notice Tell if a Result is successful. * @param _result An instance of Result. * @return `true` if successful, `false` if errored. */ function isOk(Result memory _result) public pure returns(bool) { return _result.success; } /** * @notice Tell if a Result is errored. * @param _result An instance of Result. * @return `true` if errored, `false` if successful. */ function isError(Result memory _result) public pure returns(bool) { return !_result.success; } /** * @notice Decode a bytes value from a Result as a `bytes` value. * @param _result An instance of Result. * @return The `bytes` decoded from the Result. */ function asBytes(Result memory _result) public pure returns(bytes memory) { require(_result.success, "Tried to read bytes value from errored Result"); return _result.cborValue.decodeBytes(); } /** * @notice Decode an error code from a Result as a member of `ErrorCodes`. * @param _result An instance of `Result`. * @return The `CBORValue.Error memory` decoded from the Result. */ function asErrorCode(Result memory _result) public pure returns(ErrorCodes) { uint64[] memory error = asRawError(_result); return supportedErrorOrElseUnknown(error[0]); } /** * @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments. * @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function * @param _result An instance of `Result`. * @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message. */ function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) { uint64[] memory error = asRawError(_result); ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]); bytes memory errorMessage; if (errorCode == ErrorCodes.SourceScriptNotCBOR) { errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value"); } else if (errorCode == ErrorCodes.SourceScriptNotArray) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls"); } else if (errorCode == ErrorCodes.SourceScriptNotRADON) { errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script"); } else if (errorCode == ErrorCodes.RequestTooManySources) { errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")"); } else if (errorCode == ErrorCodes.ScriptTooManyCalls) { errorMessage = abi.encodePacked( "Script #", utoa(error[2]), " from the ", stageName(error[1]), " stage contained too many calls (", utoa(error[3]), ")" ); } else if (errorCode == ErrorCodes.UnsupportedOperator) { errorMessage = abi.encodePacked( "Operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage is not supported" ); } else if (errorCode == ErrorCodes.HTTP) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved. Failed with HTTP error code: ", utoa(error[2] / 100), utoa(error[2] % 100 / 10), utoa(error[2] % 10) ); } else if (errorCode == ErrorCodes.RetrievalTimeout) { errorMessage = abi.encodePacked( "Source #", utoa(error[1]), " could not be retrieved because of a timeout." ); } else if (errorCode == ErrorCodes.Underflow) { errorMessage = abi.encodePacked( "Underflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.Overflow) { errorMessage = abi.encodePacked( "Overflow at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else if (errorCode == ErrorCodes.DivisionByZero) { errorMessage = abi.encodePacked( "Division by zero at operator code 0x", utohex(error[4]), " found at call #", utoa(error[3]), " in script #", utoa(error[2]), " from ", stageName(error[1]), " stage" ); } else { errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")"); } return (errorCode, string(errorMessage)); } /** * @notice Decode a raw error from a `Result` as a `uint64[]`. * @param _result An instance of `Result`. * @return The `uint64[]` raw error as decoded from the `Result`. */ function asRawError(Result memory _result) public pure returns(uint64[] memory) { require(!_result.success, "Tried to read error code from successful Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value. * @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. * by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. * use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asFixed16(Result memory _result) public pure returns(int32) { require(_result.success, "Tried to read `fixed16` value from errored Result"); return _result.cborValue.decodeFixed16(); } /** * @notice Decode an array of fixed16 values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asFixed16Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `fixed16[]` value from errored Result"); return _result.cborValue.decodeFixed16Array(); } /** * @notice Decode a integer numeric value from a Result as an `int128` value. * @param _result An instance of Result. * @return The `int128` decoded from the Result. */ function asInt128(Result memory _result) public pure returns(int128) { require(_result.success, "Tried to read `int128` value from errored Result"); return _result.cborValue.decodeInt128(); } /** * @notice Decode an array of integer numeric values from a Result as an `int128[]` value. * @param _result An instance of Result. * @return The `int128[]` decoded from the Result. */ function asInt128Array(Result memory _result) public pure returns(int128[] memory) { require(_result.success, "Tried to read `int128[]` value from errored Result"); return _result.cborValue.decodeInt128Array(); } /** * @notice Decode a string value from a Result as a `string` value. * @param _result An instance of Result. * @return The `string` decoded from the Result. */ function asString(Result memory _result) public pure returns(string memory) { require(_result.success, "Tried to read `string` value from errored Result"); return _result.cborValue.decodeString(); } /** * @notice Decode an array of string values from a Result as a `string[]` value. * @param _result An instance of Result. * @return The `string[]` decoded from the Result. */ function asStringArray(Result memory _result) public pure returns(string[] memory) { require(_result.success, "Tried to read `string[]` value from errored Result"); return _result.cborValue.decodeStringArray(); } /** * @notice Decode a natural numeric value from a Result as a `uint64` value. * @param _result An instance of Result. * @return The `uint64` decoded from the Result. */ function asUint64(Result memory _result) public pure returns(uint64) { require(_result.success, "Tried to read `uint64` value from errored Result"); return _result.cborValue.decodeUint64(); } /** * @notice Decode an array of natural numeric values from a Result as a `uint64[]` value. * @param _result An instance of Result. * @return The `uint64[]` decoded from the Result. */ function asUint64Array(Result memory _result) public pure returns(uint64[] memory) { require(_result.success, "Tried to read `uint64[]` value from errored Result"); return _result.cborValue.decodeUint64Array(); } /** * @notice Convert a stage index number into the name of the matching Witnet request stage. * @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages. * @return The name of the matching stage. */ function stageName(uint64 _stageIndex) public pure returns(string memory) { if (_stageIndex == 0) { return "retrieval"; } else if (_stageIndex == 1) { return "aggregation"; } else if (_stageIndex == 2) { return "tally"; } else { return "unknown"; } } /** * @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't * exist. * @param _discriminant The numeric identifier of an error. * @return A member of `ErrorCodes`. */ function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) { if (_discriminant < uint8(ErrorCodes.Size)) { return ErrorCodes(_discriminant); } else { return ErrorCodes.Unknown; } } /** * @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its. * three less significant decimal values. * @param _u A `uint64` value. * @return The `string` representing its decimal value. */ function utoa(uint64 _u) private pure returns(string memory) { if (_u < 10) { bytes memory b1 = new bytes(1); b1[0] = byte(uint8(_u) + 48); return string(b1); } else if (_u < 100) { bytes memory b2 = new bytes(2); b2[0] = byte(uint8(_u / 10) + 48); b2[1] = byte(uint8(_u % 10) + 48); return string(b2); } else { bytes memory b3 = new bytes(3); b3[0] = byte(uint8(_u / 100) + 48); b3[1] = byte(uint8(_u % 100 / 10) + 48); b3[2] = byte(uint8(_u % 10) + 48); return string(b3); } } /** * @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values. * @param _u A `uint64` value. * @return The `string` representing its hexadecimal value. */ function utohex(uint64 _u) private pure returns(string memory) { bytes memory b2 = new bytes(2); uint8 d0 = uint8(_u / 16) + 48; uint8 d1 = uint8(_u % 16) + 48; if (d0 > 57) d0 += 7; if (d1 > 57) d1 += 7; b2[0] = byte(d0); b2[1] = byte(d1); return string(b2); } } // File: witnet-ethereum-bridge/contracts/Request.sol /** * @title The serialized form of a Witnet data request */ contract Request { bytes public bytecode; uint256 public id; /** * @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized * using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using * the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests. * The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a * mismatch and a data request could be resolved with the result of another. * @param _bytecode Witnet request in bytes. */ constructor(bytes memory _bytecode) public { bytecode = _bytecode; id = uint256(sha256(_bytecode)); } } // File: witnet-ethereum-bridge/contracts/UsingWitnet.sol /** * @title The UsingWitnet contract * @notice Contract writers can inherit this contract in order to create requests for the * Witnet network. */ contract UsingWitnet { using Witnet for Witnet.Result; WitnetRequestsBoardProxy internal wrb; /** * @notice Include an address to specify the WitnetRequestsBoard. * @param _wrb WitnetRequestsBoard address. */ constructor(address _wrb) public { wrb = WitnetRequestsBoardProxy(_wrb); } // Provides a convenient way for client contracts extending this to block the execution of the main logic of the // contract until a particular request has been successfully accepted into Witnet modifier witnetRequestAccepted(uint256 _id) { require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network"); _; } // Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value modifier validRewards(uint256 _requestReward, uint256 _resultReward) { require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows"); require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards"); _; } /** * @notice Send a new request to the Witnet network * @dev Call to `post_dr` function in the WitnetRequestsBoard contract * @param _request An instance of the `Request` contract * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which posts back the request result * @return Sequencial identifier for the request included in the WitnetRequestsBoard */ function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) returns (uint256) { return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward); } /** * @notice Check if a request has been accepted into Witnet. * @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. * parties) before this method returns `true`. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though. */ function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) { // Find the request in the uint256 drHash = wrb.readDrHash(_id); // If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the // request has been proven to the WRB. return drHash != 0; } /** * @notice Upgrade the rewards for a Data Request previously included. * @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard. * @param _requestReward Reward specified for the user which posts the request into Witnet * @param _resultReward Reward specified for the user which post the Data Request result. */ function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward) internal validRewards(_requestReward, _resultReward) { wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward); } /** * @notice Read the result of a resolved request. * @dev Call to `read_result` function in the WitnetRequestsBoard contract. * @param _id The sequential identifier of a request that was posted to Witnet. * @return The result of the request as an instance of `Result`. */ function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) { return Witnet.resultFromCborBytes(wrb.readResult(_id)); } } // File: adomedianizer/contracts/IERC2362.sol /** * @dev EIP2362 Interface for pull oracles * https://github.com/tellor-io/EIP-2362 */ interface IERC2362 { /** * @dev Exposed function pertaining to EIP standards * @param _id bytes32 ID of the query * @return int,uint,uint returns the value, timestamp, and status code of query */ function valueFor(bytes32 _id) external view returns(int256,uint256,uint256); } // File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol // The bytecode of the BitcoinPrice request that will be sent to Witnet contract BitcoinPriceRequest is Request { constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the BitcoinPrice request that you created before // Your contract needs to inherit from UsingWitnet contract BtcUsdPriceFeed is UsingWitnet, IERC2362 { // The public Bitcoin price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is `keccak256("Price-BTC/USD-3")` bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new BitcoinPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != BTCUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol // The bytecode of the EthPrice request that will be sent to Witnet contract EthPriceRequest is Request { constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the ethPrice request that you created before // Your contract needs to inherit from UsingWitnet contract EthUsdPriceFeed is UsingWitnet, IERC2362 { // The public eth price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")` bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new EthPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != ETHUSD3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol // The bytecode of the GoldPrice request that will be sent to Witnet contract GoldPriceRequest is Request { constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { } } // File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol // Import the UsingWitnet library that enables interacting with Witnet // Import the ERC2362 interface // Import the goldPrice request that you created before // Your contract needs to inherit from UsingWitnet contract GoldEurPriceFeed is UsingWitnet, IERC2362 { // The public gold price point uint64 public lastPrice; // Stores the ID of the last Witnet request uint256 public lastRequestId; // Stores the timestamp of the last time the public price point was updated uint256 public timestamp; // Tells if an update has been requested but not yet completed bool public pending; // The Witnet request object, is set in the constructor Request public request; // Emits when the price is updated event priceUpdated(uint64); // Emits when found an error decoding request result event resultError(string); // This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")` bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590"); // This constructor does a nifty trick to tell the `UsingWitnet` library where // to find the Witnet contracts on whatever Ethereum network you use. constructor (address _wrb) UsingWitnet(_wrb) public { // Instantiate the Witnet request request = new GoldPriceRequest(); } /** * @notice Sends `request` to the WitnetRequestsBoard. * @dev This method will only succeed if `pending` is 0. **/ function requestUpdate() public payable { require(!pending, "An update is already pending. Complete it first before requesting another update."); // Amount to pay to the bridge node relaying this request from Ethereum to Witnet uint256 _witnetRequestReward = 100 szabo; // Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum uint256 _witnetResultReward = 100 szabo; // Send the request to Witnet and store the ID for later retrieval of the result // The `witnetPostRequest` method comes with `UsingWitnet` lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward); // Signal that there is already a pending request pending = true; } /** * @notice Reads the result, if ready, from the WitnetRequestsBoard. * @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to * protect your methods from being called before the request has been successfully * relayed into Witnet. **/ function completeUpdate() public witnetRequestAccepted(lastRequestId) { require(pending, "There is no pending update."); // Read the result of the Witnet request // The `witnetReadResult` method comes with `UsingWitnet` Witnet.Result memory result = witnetReadResult(lastRequestId); // If the Witnet request succeeded, decode the result and update the price point // If it failed, revert the transaction with a pretty-printed error message if (result.isOk()) { lastPrice = result.asUint64(); timestamp = block.timestamp; emit priceUpdated(lastPrice); } else { string memory errorMessage; // Try to read the value as an error message, catch error bytes if read fails try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) { errorMessage = e; } catch (bytes memory errorBytes){ errorMessage = string(errorBytes); } emit resultError(errorMessage); } // In any case, set `pending` to false so a new update can be requested pending = false; } /** * @notice Exposes the public data point in an ERC2362 compliant way. * @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called * successfully before. **/ function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) { // Unsupported data point ID if(_id != XAUEUR3ID) return(0, 0, 400); // No value is yet available for the queried data point ID if (timestamp == 0) return(0, 0, 404); int256 value = int256(lastPrice); return(value, timestamp, 200); } } // File: contracts/Deployer.sol // Import witnet-ethereum-block-relay-contracts // Import the UsingWitnet library that enables interacting with Witnet // Import price feeds contract Deployer { } // File: contracts/Migrations.sol contract Migrations { address public owner; uint public lastCompletedMigration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint _completed) public restricted { lastCompletedMigration = _completed; } function upgrade(address _newAddress) public restricted { Migrations upgraded = Migrations(_newAddress); upgraded.setCompleted(lastCompletedMigration); } }
@dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value. @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output. @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request. @return The unique identifier of the data request. The initial length of the `requests` array will become the ID of the request for everything related to the WRB Create a new `DataRequest` object and initialize all the non-default fields Push the new request into the contract state Let observers know that a new request has been posted
function postDataRequest(bytes calldata _serialized, uint256 _tallyReward) external payable payingEnough(msg.value, _tallyReward) override returns(uint256) { uint256 id = requests.length; DataRequest memory request; request.dr = _serialized; request.inclusionReward = SafeMath.sub(msg.value, _tallyReward); request.tallyReward = _tallyReward; requests.push(request); emit PostedRequest(msg.sender, id); return id; }
901,143
[ 1, 24983, 279, 501, 590, 1368, 326, 12984, 38, 316, 17733, 716, 518, 903, 506, 18874, 329, 471, 4640, 316, 678, 305, 2758, 598, 279, 2078, 19890, 716, 1606, 358, 1234, 18, 1132, 18, 225, 389, 17569, 1021, 1731, 4656, 358, 326, 4547, 605, 3809, 414, 11854, 434, 326, 501, 590, 876, 18, 225, 389, 88, 1230, 17631, 1060, 1021, 3844, 434, 460, 716, 903, 506, 3023, 14266, 329, 628, 326, 2492, 460, 471, 8735, 364, 19890, 310, 326, 16096, 434, 326, 727, 563, 261, 581, 69, 268, 1230, 13, 434, 326, 501, 590, 18, 327, 1021, 3089, 2756, 434, 326, 501, 590, 18, 1021, 2172, 769, 434, 326, 1375, 11420, 68, 526, 903, 12561, 326, 1599, 434, 326, 590, 364, 7756, 3746, 358, 326, 12984, 38, 1788, 279, 394, 1375, 751, 691, 68, 733, 471, 4046, 777, 326, 1661, 17, 1886, 1466, 8547, 326, 394, 590, 1368, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 18425, 691, 12, 3890, 745, 892, 389, 17569, 16, 2254, 5034, 389, 88, 1230, 17631, 1060, 13, 203, 565, 3903, 203, 565, 8843, 429, 203, 565, 8843, 310, 664, 4966, 12, 3576, 18, 1132, 16, 389, 88, 1230, 17631, 1060, 13, 203, 565, 3849, 203, 225, 1135, 12, 11890, 5034, 13, 203, 225, 288, 203, 565, 2254, 5034, 612, 273, 3285, 18, 2469, 31, 203, 203, 565, 1910, 691, 3778, 590, 31, 203, 565, 590, 18, 3069, 273, 389, 17569, 31, 203, 565, 590, 18, 267, 15335, 17631, 1060, 273, 14060, 10477, 18, 1717, 12, 3576, 18, 1132, 16, 389, 88, 1230, 17631, 1060, 1769, 203, 565, 590, 18, 88, 1230, 17631, 1060, 273, 389, 88, 1230, 17631, 1060, 31, 203, 203, 565, 3285, 18, 6206, 12, 2293, 1769, 203, 203, 565, 3626, 5616, 329, 691, 12, 3576, 18, 15330, 16, 612, 1769, 203, 203, 565, 327, 612, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; import "https://github.com/vigilance91/solidarity/contracts/accessControl/iAccessControl.sol"; import "https://github.com/vigilance91/solidarity/contracts/accessControl/AccessControlABC.sol"; /// /// @title Access Control /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 19/4/2021, All Rights Reserved /// @dev role-based access control mechanisms, /// inspired by OpenZeppelin's AccessControl contract at: /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/access/AccessControl.sol /// /// OpenZeppelin, respectfully, owns all rights to their original source in respects to its MIT license, however, /// Solidarity's version of AccessControl has been significantly rewritten from the ground up to not only increase readability but also /// reduces comment bloat, addes functionality, fixes some logic issues/potential bugs/invariants and reduce contract bytecode size /// /// Additionally, this version leverages encapsulation techniques pioneered by Solidarity, /// including the use of Constraints, Mixins, Protocols and Frameworks to extend usability, /// while still maintaining the neccessary core dependancies on OpenZeppelin, such as utils/Address and GSN/Context /// /// As such, in good spirits, this file maintains the original MIT license of OpenZeppelin's work from which it is inspired, /// the rest of the this package (which I personally wrote) is licensed under Apache-2.0 /// /// Vigilance does not claim any ownership of the original source material by OpenZepplin and acknowledges their exclusive rights, /// in respects to and as outlined by the MIT license. /// /// As such, this contract is published as free and open source software, as permitted by the MIT license. /// Vigilance does not profit from the use or distribution of this contract. /// /// Further modification to this software is permitted, /// only in respects to the original terms specified by the MIT license and must cite the original author, OpenZeppelin, /// as well as Vigilance and maintain the appropriate copyright notice and license. /// /// For more information please visit OpenZeppelin's documentation at: /// https://docs.openzeppelin.com/contracts/3.x/ /// /// NOTE: /// since Solidity does not allow embbeding comments in the compiled contract binaries. /// Due to this, in order to comply with the Apache-2.0 requirement to include the License with all binaries/executables, etc /// using EIP-926 (Global Meta-data Registry) and EIP-1753 (License Standard), /// it is possible to include/associate such license information on-chain with all contracts on the network which implement the Apache-2.0 License (or similar). /// However, there is no such requirement for the MIT license /// /// Roles are used to represent permissions and are repressented as `bytes32` identifiers and /// should be exposed in a derived contract's external API using `public constant` hash digests: /// ``` /// bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); /// ``` /// To restrict access to a function call, use {hasRole}: /// /// ``` /// function foo() public { /// require(hasRole(MY_ROLE, msg.sender)); /// ... /// } /// ``` /// OR as a modifier /// ``` /// function foo( /// )public requireRole( /// MY_ROLE, /// msg.sender /// ){ /// ... /// } /// ``` /// /// Each role has an associated admin which assigns or revokes roles dynamically via {grantRole} and {revokeRole} /// /// `DEFAULT_ADMIN_ROLE` is the default admin role for all roles, /// only addresses with this role are able to grant or revoke other roles /// /// WARNING: /// `DEFAULT_ADMIN_ROLE` is also its own admin thus, /// it has permission to grant and revoke this role /// Extra precautions should be taken to secure accounts that have been granted it, /// and is recommended that this role should only be assigned to a single address, /// potentilly either the contract deployer or owner (if ERC-173 compaliant) /// abstract contract AccessControl is AccessControlABC, //Context, iAccessControl { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; using eventsAccessControl for bytes32; using LogicConstraints for bool; using AddressConstraints for address; //using mixinAccessControl for address; //bytes32 private constant _STORAGE_SLOT = keccak256(); constructor( )internal //Context() AccessControlABC() { } /** modifier onlyRole( bytes32 role )internal { _requireHasRole(_msgSender(),role); _; } */ //helpful post-initialization, where it must be enforced 1 or more role members have been assigned a role /** function _requireRoleHasMembers( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length().requireGreaterThanZero(); } //helpful for initialization, where it must be enforced that no role members have been assigned function _requireRoleHasNoMembers( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length().requireEqualsZero(); } */ /** modifier onlyDefaultAdmin( )internal view { _requireRoleHasMembers(DEFAULT_ADMIN_ROLE); _requireIsDefaultAdmin(_msgSender()); _; } //modifier onlyDefaultAdminOrRoleAdmin( //)internal view //{ // //_; //} modifier onlyRole( bytes32 role )internal view { //_requireRoleHasMembers(role); _requireHasRole(role, _msgSender()); _; } modifier _requireNotHasRole( bytes32 role ){ _requireNotHasRole(role, _msgSender()); } modifier onlyRoleAdmin( bytes32 role ){ _requireHasAdminRole(role, _msgSender()); _; } modifier requireIsNotRoleAdmin( bytes32 role )internal view { _requireNotHasAdminRole(role, _msgSender()); _; } */ /// ///read-only interface /// /// @return {bool} `true` if `account` has been granted `role` /// /// Requirements: /// -account can not be zero address /// function hasRole( bytes32 role, address account )external view override returns( bool ){ //account.requireNotNull(); //return _roleAt(role).members.contains(account); return _hasRole(role, account); } /// /// @return {bool} `true` if `account` has been granted `role` /// /// Requirements: /// -account can not be zero address /// function hasRole( bytes32 role, address[] memory accounts )external view override returns( bool[] memory ){ return _hasRole(role, accounts); } /// /// @return {uint256} the number of accounts that have `role`, /// can be used together with {getRoleMember} to enumerate all bearers of a role /// function getRoleMemberCount( bytes32 role )public view override returns( uint256 ){ return _roleAt(role).members.length(); } /// /// @return {address} the account that have `role`, otherwise null /// `index` must be a value between 0 and {getRoleMemberCount}, non-inclusive /// /// NOTE: /// 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 /// /// for more information see: /// https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] /// function getRoleMember( bytes32 role, uint256 index )public view override returns( address ){ return _roleAt(role).members.at(index); } //function sliceRoleMembers( //bytes32 role, //uint256 start, //uint256 end //)public view override returns( //address //){ //return _roleAt(role).members.at(index); //} /// /// @return {bytes32} 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 _roleAt(role).adminRole; } /// ///mutable interface /// /// /// @dev Grants `role` to `account` /// emits a {RoleGranted} event /// /// Requirements: /// - the caller must have ``role``'s admin role /// - reverts if `account` has previously been granted `role` /// function grantRole( bytes32 role, address account )public virtual override //onlyDefaultAdminOrRoleAdmin { _requireHasAdminRole(role, _msgSender()); _grantRole(role, account); } /// /// @dev Grants `role` to each account in `accounts` /// emits multiple {RoleGranted} event /// /// Requirements: /// - the caller must have `role`'s admin role or be default admin /// - reverts if an account in `account` has previously been granted `role` /// function grantRole( bytes32 role, address[] memory accounts )public virtual override //onlyDefaultAdminOrRoleAdmin { _requireHasAdminRole(role, _msgSender()); for(uint i; i < accounts.length; i++){ _grantRole(role, accounts[i]); } } /// /// @dev Revokes `role` from `account` /// emits a {RoleRevoked} event /// /// Requirements: /// - the caller must have ``role``'s admin role /// - reverts if `account` has not previously been granted `role` /// function revokeRole( bytes32 role, address account )public virtual override { _requireHasAdminRole(role, _msgSender()); _revokeRole(role, account); } /// /// @dev Revokes `role` from `account` /// emits a {RoleRevoked} event /// /// Requirements: /// - the caller must have ``role``'s admin role /// - reverts if `account` has not previously been granted `role` /// function revokeRole( bytes32 role, address[] memory accounts )public virtual override { _requireHasAdminRole(role, _msgSender()); for(uint i; i < accounts.length; i++){ _revokeRole(role, accounts[i]); } } /// /// @dev Revokes `role` from the calling account /// Roles are often managed via {grantRole} and {revokeRole}, /// this function's provides a mechanism for accounts to lose their privileges /// if they are compromised (such as when a trusted device is misplaced) /// Emits a {RoleRevoked} event /// /// Requirements: /// - the caller must be `account` /// - caller must have been previously granted Role, otherwise revert /// function renounceRole( bytes32 role //address account )public virtual override { //account.requireEqual( //_msgSender() //"can only renounce roles for self" //); _revokeRole(role, _msgSender()); } /// /// @dev Admin forces transfer of `role` from address `from` to address `to` /// emits a {RoleRevoked} even for `from` and {RoleGranted} event for `to` /// /// Requirements: /// - the caller must have `role`'s admin role or be default admin /// - `from` must not be null and currently have the role `role` /// - `to` must not be null and not have been assigned the role `role` /// /// NOTE: /// Be careful, default admin role can be transfered (only with the privallegaes it provides), /// this is useful along with transfering ownership via ERC173 /// however, if default admin role is transfered, this will immediately prevent any further admin operations, /// thus it should be the last role transfered, if at all /// function transferRole( bytes32 role, address from, address to )public virtual override //onlyDefaultAdminOrRoleAdmin { _requireHasAdminRole(role, _msgSender()); _transferRole(role, from, to); } }
@dev Admin forces transfer of `role` from address `from` to address `to` emits a {RoleRevoked} even for `from` and {RoleGranted} event for `to` Requirements: - the caller must have `role`'s admin role or be default admin - `from` must not be null and currently have the role `role` - `to` must not be null and not have been assigned the role `role` NOTE: Be careful, default admin role can be transfered (only with the privallegaes it provides), this is useful along with transfering ownership via ERC173 however, if default admin role is transfered, this will immediately prevent any further admin operations, thus it should be the last role transfered, if at allonlyDefaultAdminOrRoleAdmin
function transferRole( bytes32 role, address from, address to )public virtual override { _requireHasAdminRole(role, _msgSender()); _transferRole(role, from, to); }
2,478,998
[ 1, 4446, 26376, 7412, 434, 1375, 4615, 68, 628, 1758, 1375, 2080, 68, 358, 1758, 1375, 869, 68, 24169, 279, 288, 2996, 10070, 14276, 97, 5456, 364, 1375, 2080, 68, 471, 288, 2996, 14570, 97, 871, 364, 1375, 869, 68, 29076, 30, 377, 300, 326, 4894, 1297, 1240, 1375, 4615, 11294, 87, 3981, 2478, 578, 506, 805, 3981, 377, 300, 1375, 2080, 68, 1297, 486, 506, 446, 471, 4551, 1240, 326, 2478, 1375, 4615, 68, 377, 300, 1375, 869, 68, 1297, 486, 506, 446, 471, 486, 1240, 2118, 6958, 326, 2478, 1375, 4615, 68, 5219, 30, 377, 4823, 26850, 16, 805, 3981, 2478, 848, 506, 7412, 329, 261, 3700, 598, 326, 846, 5162, 1935, 22335, 518, 8121, 3631, 377, 333, 353, 5301, 7563, 598, 7412, 310, 23178, 3970, 4232, 39, 31331, 377, 14025, 16, 309, 805, 3981, 2478, 353, 7412, 329, 16, 333, 903, 7636, 5309, 1281, 9271, 3981, 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, 7412, 2996, 12, 203, 3639, 1731, 1578, 2478, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 203, 565, 262, 482, 5024, 3849, 203, 565, 288, 203, 3639, 389, 6528, 5582, 4446, 2996, 12, 4615, 16, 389, 3576, 12021, 10663, 203, 540, 203, 3639, 389, 13866, 2996, 12, 4615, 16, 628, 16, 358, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= UniV3LiquidityAMO ============================= // ==================================================================== // Creates Uni v3 positions between Frax and other stablecoins/assets // Earns money on swap fees // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Jason Huan: https://github.com/jasonhuan // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Travis Moore: https://github.com/FortisFortuna import "../Frax/Frax.sol"; import "../FXS/FXS.sol"; import "../Frax/Pools/FraxPool.sol"; import "../Math/Math.sol"; import "../Math/SafeMath.sol"; import "../ERC20/ERC20.sol"; import "../ERC20/SafeERC20.sol"; import '../Uniswap/TransferHelper.sol'; import "../Staking/Owned.sol"; import "../Uniswap_V3/IUniswapV3Factory.sol"; import "../Uniswap_V3/libraries/TickMath.sol"; import "../Uniswap_V3/libraries/LiquidityAmounts.sol"; import "../Uniswap_V3/periphery/interfaces/INonfungiblePositionManager.sol"; import "../Uniswap_V3/IUniswapV3Pool.sol"; import "../Uniswap_V3/ISwapRouter.sol"; contract UniV3LiquidityAMO is Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification // Map token_id to Position mapping(uint256 => Position) public positions_mapping; // Core FRAXStablecoin private FRAX; FRAXShares private FXS; FraxPool private pool; ERC20 private pool_collateral_token; address public pool_collateral_address; uint256 public missing_decimals; address public pool_address; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Max amount of FRAX this contract can mint int256 public mint_cap = int256(1000000e18); // Tracks collateral uint256 public borrowed_collat_historical; uint256 public returned_collat_historical; // Max amount of collateral the contract can borrow from the FraxPool uint256 public collat_borrow_cap; // Minimum collateral ratio needed for new FRAX minting uint256 public min_cr; // Amount the contract borrowed int256 public minted_sum_historical = 0; int256 public burned_sum_historical = 0; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _custodian_address, address _frax_contract_address, address _fxs_contract_address, address _timelock_address, address _pool_address, address _pool_collateral_address, address _univ3_factory_address, address _univ3_positions_address, address _univ3_router_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); pool = FraxPool(_pool_address); pool_collateral_address = _pool_collateral_address; pool_collateral_token = ERC20(_pool_collateral_address); missing_decimals = uint256(18).sub(pool_collateral_token.decimals()); timelock_address = _timelock_address; custodian_address = _custodian_address; collateral_addresses.push(_pool_collateral_address); allowed_collaterals[_pool_collateral_address] = true; univ3_factory = IUniswapV3Factory(_univ3_factory_address); univ3_positions = INonfungiblePositionManager(_univ3_positions_address); univ3_router = ISwapRouter(_univ3_router_address); } /* ========== MODIFIERS ========== */ modifier onlyByOwnerOrGovernance() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnerOrGovernanceOrCustodian() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, timelock, or custodian"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = colDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function colDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); value_tally_e18 = value_tally_e18.add(col_bal_e18); } return value_tally_e18; } // Needed for the Frax contract to function function collatDollarBalance() external view returns (uint256) { return showAllocations()[3].mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // In collateral function collateralBalance() public view returns (uint256) { if (borrowed_collat_historical >= returned_collat_historical) return borrowed_collat_historical.sub(returned_collat_historical); else return 0; } // In FRAX, can be negative function mintedBalance() public view returns (int256) { return minted_sum_historical - burned_sum_historical; } // In FRAX, can be negative function accumulatedProfit() public view returns (int256) { return int256(showAllocations()[0]) - mintedBalance(); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Burn unneeded or excess FRAX function burnFRAX(uint256 amount) external onlyByOwnerOrGovernanceOrCustodian { burned_sum_historical += int256(amount); FRAX.burn(amount); } // Burn unneeded or excess FXS function burnFXS(uint256 amount) external onlyByOwnerOrGovernanceOrCustodian { FXS.approve(address(this), amount); FXS.pool_burn_from(address(this), amount); } // Give USDC profits back function giveCollatBack(uint256 amount) external onlyByOwnerOrGovernanceOrCustodian { returned_collat_historical = returned_collat_historical.add(amount); TransferHelper.safeTransfer(address(pool_collateral_token), address(pool), amount); } // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnerOrGovernanceOrCustodian { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount) public onlyByOwnerOrGovernance { ERC20(_token).approve(_target, _amount); } // f0: mint NFT using collateral / FRAX already held // uses INonfungiblePositionManager.mint() to create position // put in manual parameters to create NFT positon // if suboptimal liquidity taken, withdraw() and try again function mint(address _collateral_address, uint256 _amountCollateral, uint256 _amountFrax, uint24 _fee_tier, int24 _tickLower, int24 _tickUpper) public onlyByOwnerOrGovernance returns (uint256, uint128) { // Will revert if pool doesn't exist yet INonfungiblePositionManager.MintParams memory mint_params; if(_collateral_address < address(FRAX)){ mint_params = INonfungiblePositionManager.MintParams( _collateral_address, address(FRAX), _fee_tier, _tickLower, _tickUpper, _amountCollateral, _amountFrax, 0, 0, address(this), 2105300114 // Expiration: a long time from now ); } else { mint_params = INonfungiblePositionManager.MintParams( address(FRAX), _collateral_address, _fee_tier, _tickLower, _tickUpper, _amountFrax, _amountCollateral, 0, 0, address(this), 2105300114 // Expiration: a long time from now ); } // leave off amount0 and amount1 due to stack limit (uint256 token_id, uint128 liquidity, , ) = univ3_positions.mint(mint_params); // store new NFT in mapping and array Position memory new_position = Position(token_id, _collateral_address, liquidity, _tickLower, _tickUpper, _fee_tier); positions_mapping[token_id] = new_position; positions_array.push(new_position); return (token_id, liquidity); } // f1: withdraw current liquidity function withdraw(uint256 _token_id) public onlyByOwnerOrGovernance returns (uint256, uint256) { Position memory current_position = positions_mapping[_token_id]; INonfungiblePositionManager.DecreaseLiquidityParams memory decrease_params = INonfungiblePositionManager.DecreaseLiquidityParams( _token_id, current_position.liquidity, 0, 0, 2105300114 // Expiration: a long time from now ); univ3_positions.decreaseLiquidity(decrease_params); (uint256 amount0, uint256 amount1) = univ3_positions.collect(INonfungiblePositionManager.CollectParams( _token_id, address(this), type(uint128).max, type(uint128).max )); // Burn the empty NFT //univ3_positions.burn(_token_id); // Delete from the mapping delete positions_mapping[_token_id]; // Swap withdrawn position with last element and delete to avoid leaving a hole for (uint i = 0; i < positions_array.length; i++){ if(positions_array[i].token_id == _token_id){ positions_array[i] = positions_array[positions_array.length - 1]; positions_array.pop(); } } return (amount0, amount1); } // f2: swap tokenA into tokenB using univ3_router.ExactInputSingle() // uni v3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnerOrGovernance returns (uint256) { ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // This contract is essentially marked as a 'pool' so it can call OnlyPools functions like pool_mint and pool_burn_from // on the main FRAX contract function mintFRAXForInvestments(uint256 frax_amount) public onlyByOwnerOrGovernance { int256 frax_amt_i256 = int256(frax_amount); // Make sure you aren't minting more than the mint cap require((mintedBalance() + frax_amt_i256) <= mint_cap, "Mint cap reached"); minted_sum_historical = minted_sum_historical + frax_amt_i256; // Make sure the current CR isn't already too low require (FRAX.global_collateral_ratio() > min_cr, "Collateral ratio is already too low"); // Make sure the FRAX minting wouldn't push the CR down too much // This is also a sanity check for the int256 math uint256 current_collateral_E18 = FRAX.globalCollateralValue(); uint256 cur_frax_supply = FRAX.totalSupply(); uint256 new_frax_supply = cur_frax_supply.add(frax_amount); uint256 new_cr = (current_collateral_E18.mul(PRICE_PRECISION)).div(new_frax_supply); require (new_cr > min_cr, "Minting would cause collateral ratio to be too low"); // Mint the frax FRAX.pool_mint(address(this), frax_amount); } // It mints FRAX from nothing, and redeems it on the target pool for collateral and FXS // The burn can be called separately later on function mintRedeemPart1(uint256 frax_amount) external onlyByOwnerOrGovernance { //require(allow_yearn || allow_aave || allow_compound, 'All strategies are currently off'); uint256 redeem_amount_E6 = (frax_amount.mul(uint256(1e6).sub(pool.redemption_fee()))).div(1e6).div(10 ** missing_decimals); uint256 expected_collat_amount = redeem_amount_E6.mul(FRAX.global_collateral_ratio()).div(1e6); expected_collat_amount = expected_collat_amount.mul(1e6).div(pool.getCollateralPrice()); require(collateralBalance().add(expected_collat_amount) <= collat_borrow_cap, "Borrow cap"); borrowed_collat_historical = borrowed_collat_historical.add(expected_collat_amount); // Mint the frax FRAX.pool_mint(address(this), frax_amount); // Redeem the frax FRAX.approve(address(pool), frax_amount); pool.redeemFractionalFRAX(frax_amount, 0, 0); } function mintRedeemPart2() external onlyByOwnerOrGovernance { pool.collectRedemption(); } // Adds collateral addresses supported. Needed to make sure collatDollarBalance is correct function addCollateral(address collat_addr) public onlyByOwnerOrGovernance { require(collat_addr != address(0), "Zero address detected"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } function setCustodian(address _custodian_address) external onlyByOwnerOrGovernance { require(_custodian_address != address(0), "Custodian address cannot be 0"); custodian_address = _custodian_address; } function setTimelock(address new_timelock) external onlyByOwnerOrGovernance { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setSafetyParams(uint256 _min_cr, uint256 _mint_cap, uint256 _collat_borrow_cap) external onlyByOwnerOrGovernance { min_cr = _min_cr; mint_cap = int256(_mint_cap); collat_borrow_cap = _collat_borrow_cap; } function setPool(address _pool_address, address _pool_collateral_address, uint256 _missing_deciamls) external onlyByOwnerOrGovernance { pool_address = _pool_address; pool = FraxPool(_pool_address); pool_collateral_token = ERC20(_pool_collateral_address); pool_collateral_address = _pool_collateral_address; missing_decimals = _missing_deciamls; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnerOrGovernance { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnerOrGovernance { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FRAXStablecoin (FRAX) ====================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../Staking/Owned.sol"; import "../FXS/FXS.sol"; import "./Pools/FraxPool.sol"; import "../Oracle/UniswapPairOracle.sol"; import "../Oracle/ChainlinkETHUSDPriceConsumer.sol"; import "../Governance/AccessControl.sol"; contract FRAXStablecoin is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ enum PriceChoice { FRAX, FXS } ChainlinkETHUSDPriceConsumer private eth_usd_pricer; uint8 private eth_usd_pricer_decimals; UniswapPairOracle private fraxEthOracle; UniswapPairOracle private fxsEthOracle; string public symbol; string public name; uint8 public constant decimals = 18; address public creator_address; address public timelock_address; // Governance timelock address address public controller_address; // Controller contract to dynamically adjust system parameters automatically address public fxs_address; address public frax_eth_oracle_address; address public fxs_eth_oracle_address; address public weth_address; address public eth_usd_consumer_address; uint256 public constant genesis_supply = 2000000e18; // 2M FRAX (only for testing, genesis supply will be 5k on Mainnet). This is to help with establishing the Uniswap pools, as they need liquidity // The addresses in this array are added by the oracle and these contracts are able to mint frax address[] public frax_pools_array; // Mapping is also used for faster verification mapping(address => bool) public frax_pools; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 public global_collateral_ratio; // 6 decimals of precision, e.g. 924102 = 0.924102 uint256 public redemption_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public minting_fee; // 6 decimals of precision, divide by 1000000 in calculations for fee uint256 public frax_step; // Amount to change the collateralization ratio by upon refreshCollateralRatio() uint256 public refresh_cooldown; // Seconds to wait before being able to run refreshCollateralRatio() again uint256 public price_target; // The price of FRAX at which the collateral ratio will respond to; this value is only used for the collateral ratio mechanism and not for minting and redeeming which are hardcoded at $1 uint256 public price_band; // The bound above and below the price target at which the refreshCollateralRatio() will not change the collateral ratio address public DEFAULT_ADMIN_ADDRESS; bytes32 public constant COLLATERAL_RATIO_PAUSER = keccak256("COLLATERAL_RATIO_PAUSER"); bool public collateral_ratio_paused = false; /* ========== MODIFIERS ========== */ modifier onlyCollateralRatioPauser() { require(hasRole(COLLATERAL_RATIO_PAUSER, msg.sender)); _; } modifier onlyPools() { require(frax_pools[msg.sender] == true, "Only frax pools can call this function"); _; } modifier onlyByOwnerGovernanceOrController() { require(msg.sender == owner || msg.sender == timelock_address || msg.sender == controller_address, "Not the owner, controller, or the governance timelock"); _; } modifier onlyByOwnerGovernanceOrPool() { require( msg.sender == owner || msg.sender == timelock_address || frax_pools[msg.sender] == true, "Not the owner, the governance timelock, or a pool"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( string memory _name, string memory _symbol, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require(_timelock_address != address(0), "Zero address detected"); name = _name; symbol = _symbol; creator_address = _creator_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); DEFAULT_ADMIN_ADDRESS = _msgSender(); _mint(creator_address, genesis_supply); grantRole(COLLATERAL_RATIO_PAUSER, creator_address); grantRole(COLLATERAL_RATIO_PAUSER, timelock_address); frax_step = 2500; // 6 decimals of precision, equal to 0.25% global_collateral_ratio = 1000000; // Frax system starts off fully collateralized (6 decimals of precision) refresh_cooldown = 3600; // Refresh cooldown period is set to 1 hour (3600 seconds) at genesis price_target = 1000000; // Collateral ratio will adjust according to the $1 price target at genesis price_band = 5000; // Collateral ratio will not adjust if between $0.995 and $1.005 at genesis } /* ========== VIEWS ========== */ // Choice = 'FRAX' or 'FXS' for now function oracle_price(PriceChoice choice) internal view returns (uint256) { // Get the ETH / USD price first, and cut it down to 1e6 precision uint256 __eth_usd_price = uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); uint256 price_vs_eth = 0; if (choice == PriceChoice.FRAX) { price_vs_eth = uint256(fraxEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FRAX if you put in PRICE_PRECISION WETH } else if (choice == PriceChoice.FXS) { price_vs_eth = uint256(fxsEthOracle.consult(weth_address, PRICE_PRECISION)); // How much FXS if you put in PRICE_PRECISION WETH } else revert("INVALID PRICE CHOICE. Needs to be either 0 (FRAX) or 1 (FXS)"); // Will be in 1e6 format return __eth_usd_price.mul(PRICE_PRECISION).div(price_vs_eth); } // Returns X FRAX = 1 USD function frax_price() public view returns (uint256) { return oracle_price(PriceChoice.FRAX); } // Returns X FXS = 1 USD function fxs_price() public view returns (uint256) { return oracle_price(PriceChoice.FXS); } function eth_usd_price() public view returns (uint256) { return uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals); } // This is needed to avoid costly repeat calls to different getter functions // It is cheaper gas-wise to just dump everything and only use some of the info function frax_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return ( oracle_price(PriceChoice.FRAX), // frax_price() oracle_price(PriceChoice.FXS), // fxs_price() totalSupply(), // totalSupply() global_collateral_ratio, // global_collateral_ratio() globalCollateralValue(), // globalCollateralValue minting_fee, // minting_fee() redemption_fee, // redemption_fee() uint256(eth_usd_pricer.getLatestPrice()).mul(PRICE_PRECISION).div(uint256(10) ** eth_usd_pricer_decimals) //eth_usd_price ); } // Iterate through all frax pools and calculate all value of collateral in all pools globally function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total_collateral_value_d18.add(FraxPool(frax_pools_array[i]).collatDollarBalance()); } } return total_collateral_value_d18; } /* ========== PUBLIC FUNCTIONS ========== */ // There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion. uint256 public last_call_time; // Last time the refreshCollateralRatio function was called function refreshCollateralRatio() public { require(collateral_ratio_paused == false, "Collateral Ratio has been paused"); uint256 frax_price_cur = frax_price(); require(block.timestamp - last_call_time >= refresh_cooldown, "Must wait for the refresh cooldown since last refresh"); // Step increments are 0.25% (upon genesis, changable by setFraxStep()) if (frax_price_cur > price_target.add(price_band)) { //decrease collateral ratio if(global_collateral_ratio <= frax_step){ //if within a step of 0, go to 0 global_collateral_ratio = 0; } else { global_collateral_ratio = global_collateral_ratio.sub(frax_step); } } else if (frax_price_cur < price_target.sub(price_band)) { //increase collateral ratio if(global_collateral_ratio.add(frax_step) >= 1000000){ global_collateral_ratio = 1000000; // cap collateral ratio at 1.000000 } else { global_collateral_ratio = global_collateral_ratio.add(frax_step); } } last_call_time = block.timestamp; // Set the time of the last expansion emit CollateralRatioRefreshed(global_collateral_ratio); } /* ========== RESTRICTED FUNCTIONS ========== */ // 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 FRAXBurned(b_address, msg.sender, b_amount); } // This function is what other frax pools will call to mint new FRAX function pool_mint(address m_address, uint256 m_amount) public onlyPools { super._mint(m_address, m_amount); emit FRAXMinted(msg.sender, m_address, m_amount); } // Adds collateral addresses supported, such as tether and busd, must be ERC20 function addPool(address pool_address) public onlyByOwnerGovernanceOrController { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == false, "Address already exists"); frax_pools[pool_address] = true; frax_pools_array.push(pool_address); emit PoolAdded(pool_address); } // Remove a pool function removePool(address pool_address) public onlyByOwnerGovernanceOrController { require(pool_address != address(0), "Zero address detected"); require(frax_pools[pool_address] == true, "Address nonexistant"); // Delete from the mapping delete frax_pools[pool_address]; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_pools_array.length; i++){ if (frax_pools_array[i] == pool_address) { frax_pools_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } emit PoolRemoved(pool_address); } function setRedemptionFee(uint256 red_fee) public onlyByOwnerGovernanceOrController { redemption_fee = red_fee; emit RedemptionFeeSet(red_fee); } function setMintingFee(uint256 min_fee) public onlyByOwnerGovernanceOrController { minting_fee = min_fee; emit MintingFeeSet(min_fee); } function setFraxStep(uint256 _new_step) public onlyByOwnerGovernanceOrController { frax_step = _new_step; emit FraxStepSet(_new_step); } function setPriceTarget (uint256 _new_price_target) public onlyByOwnerGovernanceOrController { price_target = _new_price_target; emit PriceTargetSet(_new_price_target); } function setRefreshCooldown(uint256 _new_cooldown) public onlyByOwnerGovernanceOrController { refresh_cooldown = _new_cooldown; emit RefreshCooldownSet(_new_cooldown); } function setFXSAddress(address _fxs_address) public onlyByOwnerGovernanceOrController { require(_fxs_address != address(0), "Zero address detected"); fxs_address = _fxs_address; emit FXSAddressSet(_fxs_address); } function setETHUSDOracle(address _eth_usd_consumer_address) public onlyByOwnerGovernanceOrController { require(_eth_usd_consumer_address != address(0), "Zero address detected"); eth_usd_consumer_address = _eth_usd_consumer_address; eth_usd_pricer = ChainlinkETHUSDPriceConsumer(eth_usd_consumer_address); eth_usd_pricer_decimals = eth_usd_pricer.getDecimals(); emit ETHUSDOracleSet(_eth_usd_consumer_address); } function setTimelock(address new_timelock) external onlyByOwnerGovernanceOrController { require(new_timelock != address(0), "Zero address detected"); timelock_address = new_timelock; emit TimelockSet(new_timelock); } function setController(address _controller_address) external onlyByOwnerGovernanceOrController { require(_controller_address != address(0), "Zero address detected"); controller_address = _controller_address; emit ControllerSet(_controller_address); } function setPriceBand(uint256 _price_band) external onlyByOwnerGovernanceOrController { price_band = _price_band; emit PriceBandSet(_price_band); } // Sets the FRAX_ETH Uniswap oracle address function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address) public onlyByOwnerGovernanceOrController { require((_frax_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); frax_eth_oracle_address = _frax_oracle_addr; fraxEthOracle = UniswapPairOracle(_frax_oracle_addr); weth_address = _weth_address; emit FRAXETHOracleSet(_frax_oracle_addr, _weth_address); } // Sets the FXS_ETH Uniswap oracle address function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address) public onlyByOwnerGovernanceOrController { require((_fxs_oracle_addr != address(0)) && (_weth_address != address(0)), "Zero address detected"); fxs_eth_oracle_address = _fxs_oracle_addr; fxsEthOracle = UniswapPairOracle(_fxs_oracle_addr); weth_address = _weth_address; emit FXSEthOracleSet(_fxs_oracle_addr, _weth_address); } function toggleCollateralRatio() public onlyCollateralRatioPauser { collateral_ratio_paused = !collateral_ratio_paused; emit CollateralRatioToggled(collateral_ratio_paused); } /* ========== EVENTS ========== */ // Track FRAX burned event FRAXBurned(address indexed from, address indexed to, uint256 amount); // Track FRAX minted event FRAXMinted(address indexed from, address indexed to, uint256 amount); event CollateralRatioRefreshed(uint256 global_collateral_ratio); event PoolAdded(address pool_address); event PoolRemoved(address pool_address); event RedemptionFeeSet(uint256 red_fee); event MintingFeeSet(uint256 min_fee); event FraxStepSet(uint256 new_step); event PriceTargetSet(uint256 new_price_target); event RefreshCooldownSet(uint256 new_cooldown); event FXSAddressSet(address _fxs_address); event ETHUSDOracleSet(address eth_usd_consumer_address); event TimelockSet(address new_timelock); event ControllerSet(address controller_address); event PriceBandSet(uint256 price_band); event FRAXETHOracleSet(address frax_oracle_addr, address weth_address); event FXSEthOracleSet(address fxs_oracle_addr, address weth_address); event CollateralRatioToggled(bool collateral_ratio_paused); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ========================= FRAXShares (FXS) ========================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../Common/Context.sol"; import "../ERC20/ERC20Custom.sol"; import "../ERC20/IERC20.sol"; import "../Frax/Frax.sol"; import "../Staking/Owned.sol"; import "../Math/SafeMath.sol"; import "../Governance/AccessControl.sol"; contract FRAXShares is ERC20Custom, AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ string public symbol; string public name; uint8 public constant decimals = 18; address public FRAXStablecoinAdd; uint256 public constant genesis_supply = 100000000e18; // 100M is printed upon genesis address public oracle_address; address public timelock_address; // Governance timelock address FRAXStablecoin private FRAX; bool public trackingVotes = true; // Tracking votes (only change if need to disable votes) // A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(FRAX.frax_pools(msg.sender) == true, "Only frax pools can mint new FRAX"); _; } modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( string memory _name, string memory _symbol, address _oracle_address, address _creator_address, address _timelock_address ) public Owned(_creator_address){ require((_oracle_address != address(0)) && (_timelock_address != address(0)), "Zero address detected"); name = _name; symbol = _symbol; oracle_address = _oracle_address; timelock_address = _timelock_address; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _mint(_creator_address, genesis_supply); // Do a checkpoint for the owner _writeCheckpoint(_creator_address, 0, 0, uint96(genesis_supply)); } /* ========== RESTRICTED FUNCTIONS ========== */ function setOracle(address new_oracle) external onlyByOwnGov { require(new_oracle != address(0), "Zero address detected"); oracle_address = new_oracle; } function setTimelock(address new_timelock) external onlyByOwnGov { require(new_timelock != address(0), "Timelock address cannot be 0"); timelock_address = new_timelock; } function setFRAXAddress(address frax_contract_address) external onlyByOwnGov { require(frax_contract_address != address(0), "Zero address detected"); FRAX = FRAXStablecoin(frax_contract_address); emit FRAXAddressSet(frax_contract_address); } function mint(address to, uint256 amount) public onlyPools { _mint(to, amount); } // This function is what other frax pools will call to mint new FXS (similar to the FRAX mint) function pool_mint(address m_address, uint256 m_amount) external onlyPools { if(trackingVotes){ uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = add96(srcRepOld, uint96(m_amount), "pool_mint new votes overflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // mint new votes trackVotes(address(this), m_address, uint96(m_amount)); } super._mint(m_address, m_amount); emit FXSMinted(address(this), m_address, m_amount); } // This function is what other frax pools will call to burn FXS function pool_burn_from(address b_address, uint256 b_amount) external onlyPools { if(trackingVotes){ trackVotes(b_address, address(this), uint96(b_amount)); uint32 srcRepNum = numCheckpoints[address(this)]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[address(this)][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, uint96(b_amount), "pool_burn_from new votes underflows"); _writeCheckpoint(address(this), srcRepNum, srcRepOld, srcRepNew); // burn votes } super._burnFrom(b_address, b_amount); emit FXSBurned(b_address, address(this), b_amount); } function toggleVotes() external onlyByOwnGov { trackingVotes = !trackingVotes; } /* ========== OVERRIDDEN PUBLIC FUNCTIONS ========== */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(_msgSender(), recipient, uint96(amount)); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { if(trackingVotes){ // Transfer votes trackVotes(sender, recipient, uint96(amount)); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /* ========== PUBLIC FUNCTIONS ========== */ /** * @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, "FXS::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; } /* ========== INTERNAL FUNCTIONS ========== */ // From compound's _moveDelegates // Keep track of votes. "Delegates" is a misnomer here function trackVotes(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, "FXS::_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, "FXS::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address voter, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "FXS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[voter][nCheckpoints - 1].votes = newVotes; } else { checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[voter] = nCheckpoints + 1; } emit VoterVotesChanged(voter, 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; } /* ========== EVENTS ========== */ /// @notice An event thats emitted when a voters account's vote balance changes event VoterVotesChanged(address indexed voter, uint previousBalance, uint newBalance); // Track FXS burned event FXSBurned(address indexed from, address indexed to, uint256 amount); // Track FXS minted event FXSMinted(address indexed from, address indexed to, uint256 amount); event FRAXAddressSet(address addr); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ============================= FraxPool ============================= // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Reviewer(s) / Contributor(s) // Sam Sun: https://github.com/samczsun import "../../Math/SafeMath.sol"; import '../../Uniswap/TransferHelper.sol'; import "../../Staking/Owned.sol"; import "../../FXS/FXS.sol"; import "../../Frax/Frax.sol"; import "../../ERC20/ERC20.sol"; import "../../Oracle/UniswapPairOracle.sol"; import "../../Governance/AccessControl.sol"; import "./FraxPoolLibrary.sol"; contract FraxPool is AccessControl, Owned { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ ERC20 private collateral_token; address private collateral_address; address private frax_contract_address; address private fxs_contract_address; address private timelock_address; FRAXShares private FXS; FRAXStablecoin private FRAX; UniswapPairOracle private collatEthOracle; address public collat_eth_oracle_address; address private weth_address; uint256 public minting_fee; uint256 public redemption_fee; uint256 public buyback_fee; uint256 public recollat_fee; mapping (address => uint256) public redeemFXSBalances; mapping (address => uint256) public redeemCollateralBalances; uint256 public unclaimedPoolCollateral; uint256 public unclaimedPoolFXS; mapping (address => uint256) public lastRedeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // Number of decimals needed to get to 18 uint256 private immutable missing_decimals; // Pool_ceiling is the total units of collateral that a pool contract can hold uint256 public pool_ceiling = 0; // Stores price of the collateral, if price is paused uint256 public pausedPrice = 0; // Bonus rate on FXS minted during recollateralizeFRAX(); 6 decimals of precision, set to 0.75% on genesis uint256 public bonus_rate = 7500; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl Roles bytes32 private constant MINT_PAUSER = keccak256("MINT_PAUSER"); bytes32 private constant REDEEM_PAUSER = keccak256("REDEEM_PAUSER"); bytes32 private constant BUYBACK_PAUSER = keccak256("BUYBACK_PAUSER"); bytes32 private constant RECOLLATERALIZE_PAUSER = keccak256("RECOLLATERALIZE_PAUSER"); bytes32 private constant COLLATERAL_PRICE_PAUSER = keccak256("COLLATERAL_PRICE_PAUSER"); // AccessControl state variables bool public mintPaused = false; bool public redeemPaused = false; bool public recollateralizePaused = false; bool public buyBackPaused = false; bool public collateralPricePaused = false; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier notRedeemPaused() { require(redeemPaused == false, "Redeeming is paused"); _; } modifier notMintPaused() { require(mintPaused == false, "Minting is paused"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _frax_contract_address, address _fxs_contract_address, address _collateral_address, address _creator_address, address _timelock_address, uint256 _pool_ceiling ) public Owned(_creator_address){ require( (_frax_contract_address != address(0)) && (_fxs_contract_address != address(0)) && (_collateral_address != address(0)) && (_creator_address != address(0)) && (_timelock_address != address(0)) , "Zero address detected"); FRAX = FRAXStablecoin(_frax_contract_address); FXS = FRAXShares(_fxs_contract_address); frax_contract_address = _frax_contract_address; fxs_contract_address = _fxs_contract_address; collateral_address = _collateral_address; timelock_address = _timelock_address; collateral_token = ERC20(_collateral_address); pool_ceiling = _pool_ceiling; missing_decimals = uint(18).sub(collateral_token.decimals()); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(MINT_PAUSER, timelock_address); grantRole(REDEEM_PAUSER, timelock_address); grantRole(RECOLLATERALIZE_PAUSER, timelock_address); grantRole(BUYBACK_PAUSER, timelock_address); grantRole(COLLATERAL_PRICE_PAUSER, timelock_address); } /* ========== VIEWS ========== */ // Returns dollar value of collateral held in this Frax pool function collatDollarBalance() public view returns (uint256) { if(collateralPricePaused == true){ return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(pausedPrice).div(PRICE_PRECISION); } else { uint256 eth_usd_price = FRAX.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); } } // Returns the value of excess collateral held in this Frax pool, compared to what is needed to maintain the global collateral ratio function availableExcessCollatDV() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > COLLATERAL_RATIO_PRECISION) global_collateral_ratio = COLLATERAL_RATIO_PRECISION; // Handles an overcollateralized contract with CR > 1 uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(COLLATERAL_RATIO_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio if (global_collat_value > required_collat_dollar_value_d18) return global_collat_value.sub(required_collat_dollar_value_d18); else return 0; } /* ========== PUBLIC FUNCTIONS ========== */ // Returns the price of the pool collateral in USD function getCollateralPrice() public view returns (uint256) { if(collateralPricePaused == true){ return pausedPrice; } else { uint256 eth_usd_price = FRAX.eth_usd_price(); return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals))); } } function setCollatETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyByOwnGov { collat_eth_oracle_address = _collateral_weth_oracle_address; collatEthOracle = UniswapPairOracle(_collateral_weth_oracle_address); weth_address = _weth_address; } // We separate out the 1t1, fractional and algorithmic minting functions for gas efficiency function mint1t1FRAX(uint256 collateral_amount, uint256 FRAX_out_min) external notMintPaused { uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); require(FRAX.global_collateral_ratio() >= COLLATERAL_RATIO_MAX, "Collateral ratio must be >= 1"); require((collateral_token.balanceOf(address(this))).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "[Pool's Closed]: Ceiling reached"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMint1t1FRAX( getCollateralPrice(), collateral_amount_d18 ); //1 FRAX for each $1 worth of collateral frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); //remove precision at the end require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, frax_amount_d18); } // 0% collateral-backed function mintAlgorithmicFRAX(uint256 fxs_amount_d18, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); require(FRAX.global_collateral_ratio() == 0, "Collateral ratio must be 0"); (uint256 frax_amount_d18) = FraxPoolLibrary.calcMintAlgorithmicFRAX( fxs_price, // X FXS / 1 USD fxs_amount_d18 ); frax_amount_d18 = (frax_amount_d18.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= frax_amount_d18, "Slippage limit reached"); FXS.pool_burn_from(msg.sender, fxs_amount_d18); FRAX.pool_mint(msg.sender, frax_amount_d18); } // Will fail if fully collateralized or fully algorithmic // > 0% and < 100% collateral-backed function mintFractionalFRAX(uint256 collateral_amount, uint256 fxs_amount, uint256 FRAX_out_min) external notMintPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); require(collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral).add(collateral_amount) <= pool_ceiling, "Pool ceiling reached, no more FRAX can be minted with this collateral"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); FraxPoolLibrary.MintFF_Params memory input_params = FraxPoolLibrary.MintFF_Params( fxs_price, getCollateralPrice(), fxs_amount, collateral_amount_d18, global_collateral_ratio ); (uint256 mint_amount, uint256 fxs_needed) = FraxPoolLibrary.calcMintFractionalFRAX(input_params); mint_amount = (mint_amount.mul(uint(1e6).sub(minting_fee))).div(1e6); require(FRAX_out_min <= mint_amount, "Slippage limit reached"); require(fxs_needed <= fxs_amount, "Not enough FXS inputted"); FXS.pool_burn_from(msg.sender, fxs_needed); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_amount); FRAX.pool_mint(msg.sender, mint_amount); } // Redeem collateral. 100% collateral-backed function redeem1t1FRAX(uint256 FRAX_amount, uint256 COLLATERAL_out_min) external notRedeemPaused { require(FRAX.global_collateral_ratio() == COLLATERAL_RATIO_MAX, "Collateral ratio must be == 1"); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount.div(10 ** missing_decimals); (uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX( getCollateralPrice(), FRAX_amount_precision ); collateral_needed = (collateral_needed.mul(uint(1e6).sub(redemption_fee))).div(1e6); require(collateral_needed <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_needed); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_needed); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); } // Will fail if fully collateralized or algorithmic // Redeem FRAX for collateral and FXS. > 0% and < 100% collateral-backed function redeemFractionalFRAX(uint256 FRAX_amount, uint256 FXS_out_min, uint256 COLLATERAL_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio < COLLATERAL_RATIO_MAX && global_collateral_ratio > 0, "Collateral ratio needs to be between .000001 and .999999"); uint256 col_price_usd = getCollateralPrice(); uint256 FRAX_amount_post_fee = (FRAX_amount.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); uint256 fxs_dollar_value_d18 = FRAX_amount_post_fee.sub(FRAX_amount_post_fee.mul(global_collateral_ratio).div(PRICE_PRECISION)); uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); // Need to adjust for decimals of collateral uint256 FRAX_amount_precision = FRAX_amount_post_fee.div(10 ** missing_decimals); uint256 collateral_dollar_value = FRAX_amount_precision.mul(global_collateral_ratio).div(PRICE_PRECISION); uint256 collateral_amount = collateral_dollar_value.mul(PRICE_PRECISION).div(col_price_usd); require(collateral_amount <= collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral), "Not enough collateral in pool"); require(COLLATERAL_out_min <= collateral_amount, "Slippage limit reached [collateral]"); require(FXS_out_min <= fxs_amount, "Slippage limit reached [FXS]"); redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender].add(collateral_amount); unclaimedPoolCollateral = unclaimedPoolCollateral.add(collateral_amount); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // Redeem FRAX for FXS. 0% collateral-backed function redeemAlgorithmicFRAX(uint256 FRAX_amount, uint256 FXS_out_min) external notRedeemPaused { uint256 fxs_price = FRAX.fxs_price(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); require(global_collateral_ratio == 0, "Collateral ratio must be 0"); uint256 fxs_dollar_value_d18 = FRAX_amount; fxs_dollar_value_d18 = (fxs_dollar_value_d18.mul(uint(1e6).sub(redemption_fee))).div(PRICE_PRECISION); //apply fees uint256 fxs_amount = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(fxs_price); redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_amount); unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_amount); lastRedeemed[msg.sender] = block.number; require(FXS_out_min <= fxs_amount, "Slippage limit reached"); // Move all external functions to the end FRAX.pool_burn_from(msg.sender, FRAX_amount); FXS.pool_mint(address(this), fxs_amount); } // After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system. function collectRedemption() external { require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Must wait for redemption_delay blocks before collecting redemption"); bool sendFXS = false; bool sendCollateral = false; uint FXSAmount = 0; uint CollateralAmount = 0; // Use Checks-Effects-Interactions pattern if(redeemFXSBalances[msg.sender] > 0){ FXSAmount = redeemFXSBalances[msg.sender]; redeemFXSBalances[msg.sender] = 0; unclaimedPoolFXS = unclaimedPoolFXS.sub(FXSAmount); sendFXS = true; } if(redeemCollateralBalances[msg.sender] > 0){ CollateralAmount = redeemCollateralBalances[msg.sender]; redeemCollateralBalances[msg.sender] = 0; unclaimedPoolCollateral = unclaimedPoolCollateral.sub(CollateralAmount); sendCollateral = true; } if(sendFXS){ TransferHelper.safeTransfer(address(FXS), msg.sender, FXSAmount); } if(sendCollateral){ TransferHelper.safeTransfer(address(collateral_token), msg.sender, CollateralAmount); } } // When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity function recollateralizeFRAX(uint256 collateral_amount, uint256 FXS_out_min) external { require(recollateralizePaused == false, "Recollateralize is paused"); uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals); uint256 fxs_price = FRAX.fxs_price(); uint256 frax_total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); (uint256 collateral_units, uint256 amount_to_recollat) = FraxPoolLibrary.calcRecollateralizeFRAXInner( collateral_amount_d18, getCollateralPrice(), global_collat_value, frax_total_supply, global_collateral_ratio ); uint256 collateral_units_precision = collateral_units.div(10 ** missing_decimals); uint256 fxs_paid_back = amount_to_recollat.mul(uint(1e6).add(bonus_rate).sub(recollat_fee)).div(fxs_price); require(FXS_out_min <= fxs_paid_back, "Slippage limit reached"); TransferHelper.safeTransferFrom(address(collateral_token), msg.sender, address(this), collateral_units_precision); FXS.pool_mint(msg.sender, fxs_paid_back); } // Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool // This can also happen if the collateral ratio > 1 function buyBackFXS(uint256 FXS_amount, uint256 COLLATERAL_out_min) external { require(buyBackPaused == false, "Buyback is paused"); uint256 fxs_price = FRAX.fxs_price(); FraxPoolLibrary.BuybackFXS_Params memory input_params = FraxPoolLibrary.BuybackFXS_Params( availableExcessCollatDV(), fxs_price, getCollateralPrice(), FXS_amount ); (uint256 collateral_equivalent_d18) = (FraxPoolLibrary.calcBuyBackFXS(input_params)).mul(uint(1e6).sub(buyback_fee)).div(1e6); uint256 collateral_precision = collateral_equivalent_d18.div(10 ** missing_decimals); require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached"); // Give the sender their desired collateral and burn the FXS FXS.pool_burn_from(msg.sender, FXS_amount); TransferHelper.safeTransfer(address(collateral_token), msg.sender, collateral_precision); } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external { require(hasRole(MINT_PAUSER, msg.sender)); mintPaused = !mintPaused; emit MintingToggled(mintPaused); } function toggleRedeeming() external { require(hasRole(REDEEM_PAUSER, msg.sender)); redeemPaused = !redeemPaused; emit RedeemingToggled(redeemPaused); } function toggleRecollateralize() external { require(hasRole(RECOLLATERALIZE_PAUSER, msg.sender)); recollateralizePaused = !recollateralizePaused; emit RecollateralizeToggled(recollateralizePaused); } function toggleBuyBack() external { require(hasRole(BUYBACK_PAUSER, msg.sender)); buyBackPaused = !buyBackPaused; emit BuybackToggled(buyBackPaused); } function toggleCollateralPrice(uint256 _new_price) external { require(hasRole(COLLATERAL_PRICE_PAUSER, msg.sender)); // If pausing, set paused price; else if unpausing, clear pausedPrice if(collateralPricePaused == false){ pausedPrice = _new_price; } else { pausedPrice = 0; } collateralPricePaused = !collateralPricePaused; emit CollateralPriceToggled(collateralPricePaused); } // Combined into one function due to 24KiB contract memory limit function setPoolParameters(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnGov { pool_ceiling = new_ceiling; bonus_rate = new_bonus_rate; redemption_delay = new_redemption_delay; minting_fee = new_mint_fee; redemption_fee = new_redeem_fee; buyback_fee = new_buyback_fee; recollat_fee = new_recollat_fee; emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee); } function setTimelock(address new_timelock) external onlyByOwnGov { timelock_address = new_timelock; emit TimelockSet(new_timelock); } /* ========== EVENTS ========== */ event PoolParametersSet(uint256 new_ceiling, uint256 new_bonus_rate, uint256 new_redemption_delay, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee); event TimelockSet(address new_timelock); event MintingToggled(bool toggled); event RedeemingToggled(bool toggled); event RecollateralizeToggled(bool toggled); event BuybackToggled(bool toggled); event CollateralPriceToggled(bool toggled); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; 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.approve(address spender, uint256 amount) */ 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 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); } /** * @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 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 virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; 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.11; // 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.6.11; // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(int256(absTick) <= int256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './FullMath.sol'; import './FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/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.6.11; 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.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: MIT pragma solidity >=0.6.11; /* * @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 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "../Math/SafeMath.sol"; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Common/Context.sol"; import "./IERC20.sol"; import "../Math/SafeMath.sol"; import "../Utils/Address.sol"; // Due to compiling issues, _name, _symbol, and _decimals were removed /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Custom is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _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 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.approve(address spender, uint256 amount) */ 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 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); } /** * @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 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 virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Factory.sol'; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; import '../Uniswap/UniswapV2OracleLibrary.sol'; import '../Uniswap/UniswapV2Library.sol'; import "../Staking/Owned.sol"; // Fixed window oracle that recomputes the average price for the entire period once every period // Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract UniswapPairOracle is Owned { using FixedPoint for *; address timelock_address; uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price) uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale IUniswapV2Pair public immutable pair; address public immutable token0; address public immutable token1; uint public price0CumulativeLast; uint public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock"); _; } constructor (address factory, address tokenA, address tokenB, address _owner_address, address _timelock_address) public Owned(_owner_address) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair timelock_address = _timelock_address; } function setTimelock(address _timelock_address) external onlyByOwnGov { timelock_address = _timelock_address; } function setPeriod(uint _period) external onlyByOwnGov { PERIOD = _period; } function setConsultLeniency(uint _consult_leniency) external onlyByOwnGov { CONSULT_LENIENCY = _consult_leniency; } function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnGov { ALLOW_STALE_CONSULTS = _allow_stale_consults; } // Check if update() can be called instead of wasting gas calling it function canUpdate() public view returns (bool) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired return (timeElapsed >= PERIOD); } function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED'); // Overflow is desired, casting never truncates // Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // Note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint amountIn) external view returns (uint amountOut) { uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp(); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired // Ensure that the price is not stale require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE'); if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, 'UniswapPairOracle: INVALID_TOKEN'); amountOut = price1Average.mul(amountIn).decode144(); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "./AggregatorV3Interface.sol"; contract ChainlinkETHUSDPriceConsumer { AggregatorV3Interface internal priceFeed; constructor () public { priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; } function getDecimals() public view returns (uint8) { return priceFeed.decimals(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../Utils/EnumerableSet.sol"; import "../Utils/Address.sol"; import "../Common/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; //bytes32(uint256(0x4B437D01b575618140442A4975db38850e3f8f5f) << 96); /** * @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.11 <0.9.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; import "../../Math/SafeMath.sol"; library FraxPoolLibrary { using SafeMath for uint256; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; // ================ Structs ================ // Needed to lower stack size struct MintFF_Params { uint256 fxs_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 col_ratio; } struct BuybackFXS_Params { uint256 excess_collateral_dollar_value_d18; uint256 fxs_price_usd; uint256 col_price_usd; uint256 FXS_amount; } // ================ Functions ================ function calcMint1t1FRAX(uint256 col_price, uint256 collateral_amount_d18) public pure returns (uint256) { return (collateral_amount_d18.mul(col_price)).div(1e6); } function calcMintAlgorithmicFRAX(uint256 fxs_price_usd, uint256 fxs_amount_d18) public pure returns (uint256) { return fxs_amount_d18.mul(fxs_price_usd).div(1e6); } // Must be internal because of the struct function calcMintFractionalFRAX(MintFF_Params memory params) internal pure returns (uint256, uint256) { // Since solidity truncates division, every division operation must be the last operation in the equation to ensure minimum error // The contract must check the proper ratio was sent to mint FRAX. We do this by seeing the minimum mintable FRAX based on each amount uint256 fxs_dollar_value_d18; uint256 c_dollar_value_d18; // Scoping for stack concerns { // USD amounts of the collateral and the FXS fxs_dollar_value_d18 = params.fxs_amount.mul(params.fxs_price_usd).div(1e6); c_dollar_value_d18 = params.collateral_amount.mul(params.col_price_usd).div(1e6); } uint calculated_fxs_dollar_value_d18 = (c_dollar_value_d18.mul(1e6).div(params.col_ratio)) .sub(c_dollar_value_d18); uint calculated_fxs_needed = calculated_fxs_dollar_value_d18.mul(1e6).div(params.fxs_price_usd); return ( c_dollar_value_d18.add(calculated_fxs_dollar_value_d18), calculated_fxs_needed ); } function calcRedeem1t1FRAX(uint256 col_price_usd, uint256 FRAX_amount) public pure returns (uint256) { return FRAX_amount.mul(1e6).div(col_price_usd); } // Must be internal because of the struct function calcBuyBackFXS(BuybackFXS_Params memory params) internal pure returns (uint256) { // If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral require(params.excess_collateral_dollar_value_d18 > 0, "No excess collateral to buy back!"); // Make sure not to take more than is available uint256 fxs_dollar_value_d18 = params.FXS_amount.mul(params.fxs_price_usd).div(1e6); require(fxs_dollar_value_d18 <= params.excess_collateral_dollar_value_d18, "You are trying to buy back more than the excess!"); // Get the equivalent amount of collateral based on the market value of FXS provided uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(1e6).div(params.col_price_usd); //collateral_equivalent_d18 = collateral_equivalent_d18.sub((collateral_equivalent_d18.mul(params.buyback_fee)).div(1e6)); return ( collateral_equivalent_d18 ); } // Returns value of collateral that must increase to reach recollateralization target (if 0 means no recollateralization) function recollateralizeAmount(uint256 total_supply, uint256 global_collateral_ratio, uint256 global_collat_value) public pure returns (uint256) { uint256 target_collat_value = total_supply.mul(global_collateral_ratio).div(1e6); // We want 18 decimals of precision so divide by 1e6; total_supply is 1e18 and global_collateral_ratio is 1e6 // Subtract the current value of collateral from the target value needed, if higher than 0 then system needs to recollateralize return target_collat_value.sub(global_collat_value); // If recollateralization is not needed, throws a subtraction underflow // return(recollateralization_left); } function calcRecollateralizeFRAXInner( uint256 collateral_amount, uint256 col_price, uint256 global_collat_value, uint256 frax_total_supply, uint256 global_collateral_ratio ) public pure returns (uint256, uint256) { uint256 collat_value_attempted = collateral_amount.mul(col_price).div(1e6); uint256 effective_collateral_ratio = global_collat_value.mul(1e6).div(frax_total_supply); //returns it in 1e6 uint256 recollat_possible = (global_collateral_ratio.mul(frax_total_supply).sub(frax_total_supply.mul(effective_collateral_ratio))).div(1e6); uint256 amount_to_recollat; if(collat_value_attempted <= recollat_possible){ amount_to_recollat = collat_value_attempted; } else { amount_to_recollat = recollat_possible; } return (amount_to_recollat.mul(1e6).div(col_price), amount_to_recollat); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /** * @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(bytes20(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(bytes20(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(bytes20(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(bytes20(_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.11; 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // 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); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // 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); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; import '../Math/FixedPoint.sol'; // 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; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import './Interfaces/IUniswapV2Pair.sol'; import './Interfaces/IUniswapV2Factory.sol'; import "../Math/SafeMath.sol"; 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'); } // Less efficient than the CREATE2 method below function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); } // calculates the CREATE2 address for a pair without making any external calls function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(bytes20(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); // this matches the CREATE2 in UniswapV2Factory.createPair } // 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 = 0; 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); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // 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 "../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: 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; 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; /// @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.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.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(uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) )); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.11; /// @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.6.11; /// @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: MIT pragma solidity >=0.6.11; /// @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: MIT pragma solidity >=0.6.11; /// @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.6.11; /// @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.6.11; /// @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 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; }
@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; } pragma solidity >=0.5.0; struct PoolKey { address token0; address token1; uint24 fee; } 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}); function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address(uint160( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) )); } }
524,658
[ 1, 17727, 4186, 364, 4854, 9288, 279, 2845, 1758, 628, 326, 3272, 16, 2430, 16, 471, 326, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 8828, 1887, 288, 203, 565, 1731, 1578, 2713, 5381, 13803, 1741, 67, 12919, 67, 5572, 67, 15920, 273, 374, 6554, 5026, 74, 19818, 70, 3657, 70, 22, 70, 24, 74, 9462, 74, 26, 5193, 24, 5558, 3657, 72, 27982, 5324, 72, 3247, 24, 74, 8285, 69, 1578, 10580, 24852, 6675, 1578, 25, 74, 5193, 23, 74, 11035, 70, 28, 70, 6564, 31, 203, 203, 97, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 20, 31, 203, 565, 1958, 8828, 653, 288, 203, 3639, 1758, 1147, 20, 31, 203, 3639, 1758, 1147, 21, 31, 203, 3639, 2254, 3247, 14036, 31, 203, 565, 289, 203, 203, 565, 445, 28575, 653, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 3247, 14036, 203, 565, 262, 2713, 16618, 1135, 261, 2864, 653, 3778, 13, 288, 203, 3639, 309, 261, 2316, 37, 405, 1147, 38, 13, 261, 2316, 37, 16, 1147, 38, 13, 273, 261, 2316, 38, 16, 1147, 37, 1769, 203, 565, 289, 203, 203, 3639, 327, 8828, 653, 12590, 2316, 20, 30, 1147, 37, 16, 1147, 21, 30, 1147, 38, 16, 14036, 30, 14036, 22938, 203, 565, 445, 3671, 1887, 12, 2867, 3272, 16, 8828, 653, 3778, 498, 13, 2713, 16618, 1135, 261, 2867, 2845, 13, 288, 203, 3639, 2583, 12, 856, 18, 2316, 20, 411, 498, 18, 2316, 21, 1769, 203, 3639, 2845, 273, 1758, 12, 11890, 16874, 12, 203, 5411, 2254, 5034, 12, 203, 7734, 417, 24410, 581, 5034, 12, 203, 10792, 24126, 18, 3015, 2 ]
./full_match/4/0x98524FE45cBb1c43D7e31667381327fcbf2A8dD6/sources/docs.chain.link/samples/VRF/VRFD20.sol
* @notice Requests randomness @dev Warning: if the VRF response is delayed, avoid calling requestRandomness repeatedly as that would give miners/VRF operators latitude about which VRF response arrives first. @dev You must review your implementation details with extreme care. @param roller address of the roller/ Will revert if subscription is not set and funded.
function rollDice(address roller) public onlyOwner returns (uint256 requestId) { require(s_results[roller] == 0, 'Already rolled'); requestId = COORDINATOR.requestRandomWords( s_keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords ); s_rollers[requestId] = roller; s_results[roller] = ROLL_IN_PROGRESS; emit DiceRolled(requestId, roller); }
647,847
[ 1, 6421, 2744, 4496, 225, 9728, 30, 309, 326, 776, 12918, 766, 353, 15278, 16, 4543, 4440, 590, 8529, 4496, 30412, 487, 716, 4102, 8492, 1131, 414, 19, 10986, 42, 12213, 8904, 2973, 1492, 776, 12918, 766, 2454, 3606, 1122, 18, 225, 4554, 1297, 10725, 3433, 4471, 3189, 598, 23755, 73, 7671, 18, 225, 10643, 749, 1758, 434, 326, 10643, 749, 19, 9980, 15226, 309, 4915, 353, 486, 444, 471, 9831, 785, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5824, 40, 1812, 12, 2867, 10643, 749, 13, 1071, 1338, 5541, 1135, 261, 11890, 5034, 14459, 13, 288, 203, 3639, 2583, 12, 87, 67, 4717, 63, 1539, 65, 422, 374, 16, 296, 9430, 28693, 8284, 203, 3639, 14459, 273, 7910, 916, 21329, 3575, 18, 2293, 8529, 7363, 12, 203, 5411, 272, 67, 856, 2310, 16, 203, 5411, 272, 67, 25218, 16, 203, 5411, 590, 11269, 1012, 16, 203, 5411, 1348, 27998, 3039, 16, 203, 5411, 818, 7363, 203, 3639, 11272, 203, 203, 3639, 272, 67, 7484, 63, 2293, 548, 65, 273, 10643, 749, 31, 203, 3639, 272, 67, 4717, 63, 1539, 65, 273, 534, 30922, 67, 706, 67, 24022, 31, 203, 3639, 3626, 463, 1812, 4984, 1259, 12, 2293, 548, 16, 10643, 749, 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 ]
// Copyright (C) 2018 Alon Bukai 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, 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/ // Original ideas here https://github.com/Alonski/MultiSendEthereum/blob/master/contracts/MultiSend.sol pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @notice `MultiSend` is a contract for sending multiple ETH/ERC20 Tokens to /// multiple addresses. In addition this contract can call multiple contracts /// with multiple amounts. There are also TightlyPacked functions which in /// some situations allow for gas savings. TightlyPacked is cheaper if you /// need to store input data and if amount is less than 12 bytes. Normal is /// cheaper if you don't need to store input data or if amounts are greater /// than 12 bytes. 12 bytes allows for sends of up to 2^96-1 units, 79 billion /// ETH, so tightly packed functions will work for any ETH send but may not /// work for token sends when the token has a high number of decimals or a /// very large total supply. Supports deterministic deployment. As explained /// here: https://github.com/ethereum/EIPs/issues/777#issuecomment-356103528 contract MultiSend is Ownable { address internal constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; using SafeERC20 for IERC20; using SafeMath for uint256; struct Send { address token; address to; uint256 amount; } event Call(address indexed _from, address indexed _to, uint256 _amount); constructor() public {} function multiSend(Send[] calldata sends) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < sends.length; i++) { if (sends[i].token == NATIVE_TOKEN) { _safeCall(sends[i].to, sends[i].amount); sentAmount = sentAmount.add(sends[i].amount); } else { IERC20(sends[i].token).safeTransferFrom(msg.sender, sends[i].to, sends[i].amount); } } require(sentAmount == msg.value, "mismatch send amount"); return true; } /// @notice Call to multiple contracts using a byte32 array which /// includes the contract address and the amount. /// Addresses and amounts are stored in a packed bytes32 array. /// Address is stored in the 20 most significant bytes. /// The address is retrieved by bitshifting 96 bits to the right /// Amount is stored in the 12 least significant bytes. /// The amount is retrieved by taking the 96 least significant bytes /// and converting them into an unsigned integer. /// Payable /// @param _addressesAndAmounts Bitwise packed array of contract /// addresses and amounts function multiCallTightlyPacked(bytes32[] calldata _addressesAndAmounts) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { address to = address(bytes20(_addressesAndAmounts[i])); uint256 amount = uint256(uint96(uint256(_addressesAndAmounts[i]))); _safeCall(to, amount); sentAmount = sentAmount.add(amount); } require(sentAmount == msg.value, "mismatch send amount"); return true; } /// @notice Call to multiple contracts using two arrays which /// includes the contract address and the amount. /// @param _addresses Array of contract addresses to call /// @param _amounts Array of amounts to send function multiCall(address[] calldata _addresses, uint256[] calldata _amounts) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < _addresses.length; i++) { _safeCall(_addresses[i], _amounts[i]); sentAmount = sentAmount.add(_amounts[i]); } require(sentAmount == msg.value, "mismatch send amount"); return true; } /// @notice Send ERC20 tokens to multiple contracts /// using a byte32 array which includes the address and the amount. /// Addresses and amounts are stored in a packed bytes32 array. /// Address is stored in the 20 most significant bytes. /// The address is retrieved by bitshifting 96 bits to the right /// Amount is stored in the 12 least significant bytes. /// The amount is retrieved by taking the 96 least significant bytes /// and converting them into an unsigned integer. /// @param _token The token to send /// @param _addressesAndAmounts Bitwise packed array of addresses /// and token amounts function multiERC20TransferTightlyPacked( address _token, bytes32[] calldata _addressesAndAmounts ) external { for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { address to = address(bytes20(_addressesAndAmounts[i])); uint256 amount = uint256(uint96(uint256(_addressesAndAmounts[i]))); IERC20(_token).safeTransferFrom(msg.sender, to, amount); } } /// @notice Send ERC20 tokens to multiple contracts /// using two arrays which includes the address and the amount. /// @param _token The token to send /// @param _addresses Array of addresses to send to /// @param _amounts Array of token amounts to send function multiERC20Transfer( address _token, address[] calldata _addresses, uint256[] calldata _amounts ) external { for (uint256 i = 0; i < _addresses.length; i++) { IERC20(_token).safeTransferFrom(msg.sender, _addresses[i], _amounts[i]); } } function withdraw( address token, uint256 amount, address to ) external onlyOwner { if (token == NATIVE_TOKEN) { _safeCall(to, amount); } else { IERC20(token).safeTransfer(to, amount); } } receive() external payable {} function _safeCall(address to, uint256 amount) internal { (bool success, ) = to.call{value: amount}(""); require(success, "transfer eth failed"); emit Call(msg.sender, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
@notice `MultiSend` is a contract for sending multiple ETH/ERC20 Tokens to multiple addresses. In addition this contract can call multiple contracts with multiple amounts. There are also TightlyPacked functions which in some situations allow for gas savings. TightlyPacked is cheaper if you need to store input data and if amount is less than 12 bytes. Normal is cheaper if you don't need to store input data or if amounts are greater than 12 bytes. 12 bytes allows for sends of up to 2^96-1 units, 79 billion ETH, so tightly packed functions will work for any ETH send but may not work for token sends when the token has a high number of decimals or a very large total supply. Supports deterministic deployment. As explained here: https://github.com/ethereum/EIPs/issues/777#issuecomment-356103528
contract MultiSend is Ownable { address internal constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; using SafeERC20 for IERC20; using SafeMath for uint256; struct Send { address token; address to; uint256 amount; } event Call(address indexed _from, address indexed _to, uint256 _amount); constructor() public {} function multiSend(Send[] calldata sends) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < sends.length; i++) { if (sends[i].token == NATIVE_TOKEN) { _safeCall(sends[i].to, sends[i].amount); sentAmount = sentAmount.add(sends[i].amount); IERC20(sends[i].token).safeTransferFrom(msg.sender, sends[i].to, sends[i].amount); } } require(sentAmount == msg.value, "mismatch send amount"); return true; } function multiSend(Send[] calldata sends) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < sends.length; i++) { if (sends[i].token == NATIVE_TOKEN) { _safeCall(sends[i].to, sends[i].amount); sentAmount = sentAmount.add(sends[i].amount); IERC20(sends[i].token).safeTransferFrom(msg.sender, sends[i].to, sends[i].amount); } } require(sentAmount == msg.value, "mismatch send amount"); return true; } function multiSend(Send[] calldata sends) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < sends.length; i++) { if (sends[i].token == NATIVE_TOKEN) { _safeCall(sends[i].to, sends[i].amount); sentAmount = sentAmount.add(sends[i].amount); IERC20(sends[i].token).safeTransferFrom(msg.sender, sends[i].to, sends[i].amount); } } require(sentAmount == msg.value, "mismatch send amount"); return true; } } else { function multiCallTightlyPacked(bytes32[] calldata _addressesAndAmounts) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { address to = address(bytes20(_addressesAndAmounts[i])); uint256 amount = uint256(uint96(uint256(_addressesAndAmounts[i]))); _safeCall(to, amount); sentAmount = sentAmount.add(amount); } require(sentAmount == msg.value, "mismatch send amount"); return true; } function multiCallTightlyPacked(bytes32[] calldata _addressesAndAmounts) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { address to = address(bytes20(_addressesAndAmounts[i])); uint256 amount = uint256(uint96(uint256(_addressesAndAmounts[i]))); _safeCall(to, amount); sentAmount = sentAmount.add(amount); } require(sentAmount == msg.value, "mismatch send amount"); return true; } function multiCall(address[] calldata _addresses, uint256[] calldata _amounts) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < _addresses.length; i++) { _safeCall(_addresses[i], _amounts[i]); sentAmount = sentAmount.add(_amounts[i]); } require(sentAmount == msg.value, "mismatch send amount"); return true; } function multiCall(address[] calldata _addresses, uint256[] calldata _amounts) external payable returns (bool) { uint256 sentAmount = 0; for (uint256 i = 0; i < _addresses.length; i++) { _safeCall(_addresses[i], _amounts[i]); sentAmount = sentAmount.add(_amounts[i]); } require(sentAmount == msg.value, "mismatch send amount"); return true; } function multiERC20TransferTightlyPacked( address _token, bytes32[] calldata _addressesAndAmounts ) external { for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { address to = address(bytes20(_addressesAndAmounts[i])); uint256 amount = uint256(uint96(uint256(_addressesAndAmounts[i]))); IERC20(_token).safeTransferFrom(msg.sender, to, amount); } } function multiERC20TransferTightlyPacked( address _token, bytes32[] calldata _addressesAndAmounts ) external { for (uint256 i = 0; i < _addressesAndAmounts.length; i++) { address to = address(bytes20(_addressesAndAmounts[i])); uint256 amount = uint256(uint96(uint256(_addressesAndAmounts[i]))); IERC20(_token).safeTransferFrom(msg.sender, to, amount); } } function multiERC20Transfer( address _token, address[] calldata _addresses, uint256[] calldata _amounts ) external { for (uint256 i = 0; i < _addresses.length; i++) { IERC20(_token).safeTransferFrom(msg.sender, _addresses[i], _amounts[i]); } } function multiERC20Transfer( address _token, address[] calldata _addresses, uint256[] calldata _amounts ) external { for (uint256 i = 0; i < _addresses.length; i++) { IERC20(_token).safeTransferFrom(msg.sender, _addresses[i], _amounts[i]); } } function withdraw( address token, uint256 amount, address to ) external onlyOwner { if (token == NATIVE_TOKEN) { _safeCall(to, amount); IERC20(token).safeTransfer(to, amount); } } function withdraw( address token, uint256 amount, address to ) external onlyOwner { if (token == NATIVE_TOKEN) { _safeCall(to, amount); IERC20(token).safeTransfer(to, amount); } } } else { receive() external payable {} function _safeCall(address to, uint256 amount) internal { require(success, "transfer eth failed"); emit Call(msg.sender, to, amount); } (bool success, ) = to.call{value: amount}(""); }
1,580,182
[ 1, 68, 5002, 3826, 68, 353, 279, 6835, 364, 5431, 3229, 512, 2455, 19, 654, 39, 3462, 13899, 358, 225, 3229, 6138, 18, 657, 2719, 333, 6835, 848, 745, 3229, 20092, 225, 598, 3229, 30980, 18, 6149, 854, 2546, 399, 750, 715, 4420, 329, 4186, 1492, 316, 225, 2690, 28474, 1699, 364, 16189, 4087, 899, 18, 399, 750, 715, 4420, 329, 353, 19315, 7294, 309, 1846, 225, 1608, 358, 1707, 810, 501, 471, 309, 3844, 353, 5242, 2353, 2593, 1731, 18, 8769, 353, 225, 19315, 7294, 309, 1846, 2727, 1404, 1608, 358, 1707, 810, 501, 578, 309, 30980, 854, 6802, 225, 2353, 2593, 1731, 18, 2593, 1731, 5360, 364, 9573, 434, 731, 358, 576, 66, 10525, 17, 21, 4971, 16, 26517, 20714, 285, 225, 512, 2455, 16, 1427, 26066, 715, 12456, 4186, 903, 1440, 364, 1281, 512, 2455, 1366, 1496, 2026, 486, 225, 1440, 364, 1147, 9573, 1347, 326, 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, 5991, 3826, 353, 14223, 6914, 288, 203, 565, 1758, 2713, 5381, 423, 12992, 67, 8412, 273, 374, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 1958, 2479, 288, 203, 3639, 1758, 1147, 31, 203, 3639, 1758, 358, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 565, 289, 203, 203, 565, 871, 3049, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 2254, 5034, 389, 8949, 1769, 203, 203, 203, 565, 3885, 1435, 1071, 2618, 203, 565, 445, 3309, 3826, 12, 3826, 8526, 745, 892, 9573, 13, 3903, 8843, 429, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 3271, 6275, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 9573, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 4661, 87, 63, 77, 8009, 2316, 422, 423, 12992, 67, 8412, 13, 288, 203, 7734, 389, 4626, 1477, 12, 4661, 87, 63, 77, 8009, 869, 16, 9573, 63, 77, 8009, 8949, 1769, 203, 7734, 3271, 6275, 273, 3271, 6275, 18, 1289, 12, 4661, 87, 63, 77, 8009, 8949, 1769, 203, 7734, 467, 654, 39, 3462, 12, 4661, 87, 63, 77, 8009, 2316, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 9573, 63, 77, 8009, 869, 16, 9573, 2 ]
pragma solidity ^0.4.22; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) external { from_; value_; data_; revert(); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract SwaceToken is DetailedERC20, PausableToken, CappedToken, HasNoTokens, HasNoEther { event Finalize(uint256 value); event ChangeVestingAgent(address indexed oldVestingAgent, address indexed newVestingAgent); uint256 private constant TOKEN_UNIT = 10 ** uint256(18); uint256 public constant TOTAL_SUPPLY = 2700e6 * TOKEN_UNIT; uint256 public constant COMMUNITY_SUPPLY = 621e6 * TOKEN_UNIT; uint256 public constant TEAM_SUPPLY = 324e6 * TOKEN_UNIT; uint256 public constant ADV_BTY_SUPPLY = 270e6 * TOKEN_UNIT; address public advBtyWallet; address public communityWallet; address public vestingAgent; bool public finalized = false; modifier onlyVestingAgent() { require(msg.sender == vestingAgent); _; } modifier whenNotFinalized() { require(!finalized); _; } constructor( address _communityWallet, address _teamWallet, address _advBtyWallet ) public DetailedERC20("Swace", "SWA", 18) CappedToken(TOTAL_SUPPLY) { // solium-disable-next-line security/no-block-members require(_communityWallet != address(0)); require(_teamWallet != address(0)); require(_advBtyWallet != address(0)); communityWallet = _communityWallet; advBtyWallet = _advBtyWallet; //Team wallet is actually vesting agent contract changeVestingAgent(_teamWallet); //Mint tokens to defined wallets mint(_communityWallet, COMMUNITY_SUPPLY); mint(_teamWallet, TEAM_SUPPLY); mint(_advBtyWallet, ADV_BTY_SUPPLY); //Mint owner with the rest of tokens mint(owner, TOTAL_SUPPLY.sub(totalSupply_)); //Finish minting because we minted everything already finishMinting(); } /** * @dev Original ERC20 approve with additional security mesure. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address _spender, uint256 _value) public returns (bool) { //https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); return super.approve(_spender, _value); } /** * @dev Do finalization. * @return A boolean that indicates if the operation was successful. */ function finalize() public onlyOwner whenNotFinalized returns (bool) { uint256 ownerBalance = balanceOf(owner); //Transfer what is left in owner to community wallet if (ownerBalance > 0) { transfer(communityWallet, ownerBalance); } uint256 advBtyBalance = balanceOf(advBtyWallet); //Transfer what is left in advisor & bounty wallet to community wallet //TODO: does not work probably because there is no approval if (advBtyBalance > 0) { transferFrom(advBtyWallet, communityWallet, advBtyBalance); } finalized = true; emit Finalize(ownerBalance.add(advBtyBalance)); return true; } /** * TODO: add check if _vestingAgent is contract address * @dev Allow to change vesting agent. * @param _vestingAgent The address of new vesting agent. */ function changeVestingAgent(address _vestingAgent) public onlyOwner { address oldVestingAgent = vestingAgent; vestingAgent = _vestingAgent; emit ChangeVestingAgent(oldVestingAgent, _vestingAgent); } }
* TODO: add check if _vestingAgent is contract address @dev Allow to change vesting agent. @param _vestingAgent The address of new vesting agent./
function changeVestingAgent(address _vestingAgent) public onlyOwner { address oldVestingAgent = vestingAgent; vestingAgent = _vestingAgent; emit ChangeVestingAgent(oldVestingAgent, _vestingAgent); }
2,543,461
[ 1, 6241, 30, 527, 866, 309, 389, 90, 10100, 3630, 353, 6835, 1758, 225, 7852, 358, 2549, 331, 10100, 4040, 18, 225, 389, 90, 10100, 3630, 1021, 1758, 434, 394, 331, 10100, 4040, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2549, 58, 10100, 3630, 12, 2867, 389, 90, 10100, 3630, 13, 203, 565, 1071, 203, 565, 1338, 5541, 203, 225, 288, 203, 565, 1758, 1592, 58, 10100, 3630, 273, 331, 10100, 3630, 31, 203, 565, 331, 10100, 3630, 273, 389, 90, 10100, 3630, 31, 203, 203, 565, 3626, 7576, 58, 10100, 3630, 12, 1673, 58, 10100, 3630, 16, 389, 90, 10100, 3630, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-10-29 */ /* Keep4r 1 kp4r.network - 2020 */ pragma solidity 0.6.6; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } contract Keep4rPresale { using SafeMath for uint256; // cannot purchase until started bool internal started; IERC20 KP4R; address kp4rAddress; address internal manager; address internal managerPending; uint256 constant managerS = 80; uint256 internal managerWithdrawn; address internal overseer; address internal overseerPending; uint256 constant overseerS = 20; uint256 internal overseerWithdrawn; uint256 internal unitPrice = 1e18/2; uint256 internal minimumOrder = 100000; /** @notice the date when purchased KP4R can be claimed */ uint256 internal unlocksOn; /** @notice the date when KP4R can no longer be purchased from the contract */ uint256 internal endsOn; /** @notice percentage bonus actived upon purchasing more than the trigger * value. */ uint256 internal bonusTrigger; uint256 internal bonusPercentage; // Stats: uint256 internal totalForSale; uint256 internal totalSold; uint256 internal totalSettled; uint256 internal weiRaised; mapping(address => uint256) internal balance; event Purchase (address indexed buyer, uint256 amount, uint256 price); constructor(address _kp4r) public { manager = msg.sender; overseer = msg.sender; KP4R = IERC20(_kp4r); kp4rAddress = _kp4r; } modifier onlyManager { require( msg.sender == manager, "Only the manager can call this function." ); _; } modifier onlyOverseer { require( msg.sender == overseer, "Only the overseer can call this function."); _; } function transferRole(address _new) public { require(msg.sender == manager || msg.sender == overseer, "!manager or overseer"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == manager) { managerPending = _new; return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == overseer) { overseerPending = _new; return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function acceptRole() public { require(msg.sender == managerPending || msg.sender == overseerPending, "!managerPending or overseerPending"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == managerPending) { manager = managerPending; managerPending = address(0); return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (msg.sender == overseerPending) { overseer = overseerPending; managerPending = address(0); return; } //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerSetPrice(uint256 _price) public onlyManager { unitPrice = _price; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerSetMinimum(uint256 _minimum) public onlyManager { minimumOrder = _minimum; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerSetBonus(uint256 _trigger, uint256 _percentage) public onlyManager { bonusTrigger = _trigger; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC bonusPercentage = _percentage; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerDeposit(uint256 _amount) public onlyManager { KP4R.transferFrom(msg.sender, address(this), _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalForSale = totalForSale.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** @notice manager can reclaim unsold tokens */ function managerReclaim(uint256 _amount) public onlyManager { // calculate the amount of tokens that haven not been sold // and settled and are thus reclaimable: uint256 unreclaimable = totalSold.sub(totalSettled); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 reclaimable = KP4R.balanceOf(address(this)).sub(unreclaimable); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(_amount <= reclaimable, "cannot withdraw already sold tokens"); // transfer the tokens to the manager KP4R.transfer(msg.sender, _amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalForSale = totalForSale.sub(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function managerWithdraw(uint256 _amount) public onlyManager { require(managerWithdrawn.add(_amount) <= weiRaised.mul(managerS).div(100), "cannot withdraw more than the managers share"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC managerWithdrawn = managerWithdrawn.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC msg.sender.transfer(_amount); } function overseerWithdraw(uint _amount) public onlyOverseer { require(overseerWithdrawn.add(_amount) <= weiRaised.mul(overseerS).div(100), "cannot withdraw more than overseerS"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC overseerWithdrawn = overseerWithdrawn.add(_amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC msg.sender.transfer(_amount); } function managerClose(uint256 amount) public onlyManager { require(block.timestamp > endsOn.add(31536000).mul(2), "must wait until 6 months past end date"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC msg.sender.transfer(amount); } function managerForceUnlock() public onlyManager { unlocksOn = block.timestamp-1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function start(uint256 _unlocksOn, uint256 _endsOn, uint256 _price, uint256 _minimumOrder) public onlyManager { require(!started, "already started"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC unlocksOn = _unlocksOn; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC endsOn = _endsOn; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC unitPrice = _price; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC minimumOrder = _minimumOrder; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC started = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** @notice The amount of KP4R remaining */ function remaining() public view returns (uint256) { return KP4R.balanceOf(address(this)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** @notice purchase KP4R at the current unit price */ function purchase() public payable { require(started, "token sale has not yet started"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(msg.value > minimumOrder, "amount purchased is too small"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(block.timestamp < endsOn, "presale has ended"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // calculate the amount of KP4R purchasable uint256 _kp4r = calculateAmountPurchased(msg.value); require(_kp4r <= KP4R.balanceOf(address(this)), "not enough KP4R left"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // update the users balance balance[msg.sender] = balance[msg.sender].add(_kp4r); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalSold = totalSold.add(_kp4r); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC weiRaised = weiRaised.add(msg.value); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC emit Purchase(msg.sender, _kp4r, msg.value); } /** @notice calculates the amount purchasedfor a given amount of eth */ function calculateAmountPurchased(uint256 _value) public view returns (uint256) { uint256 _kp4r = _value.div(unitPrice).mul(1e18); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_value > bonusTrigger) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC uint256 _bonus = _kp4r.mul(bonusPercentage).div(1000); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC if (_kp4r.add(_bonus) <= KP4R.balanceOf(address(this))) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _kp4r = _kp4r.add(_bonus); } } return _kp4r; } /** @notice claim you eth */ function claim() public { require(block.timestamp > unlocksOn, "presale has not unlocked yet"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC require(balance[msg.sender] > 0, "nothing to withdraw"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC KP4R.transfer(msg.sender, balance[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalSettled = totalSettled.add(balance[msg.sender]); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } // fallbacks to allow users to send to the contract to purchase KP4R receive() external payable { purchase(); } fallback() external payable { purchase(); } }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalSold = totalSold.add(_kp4r);
7,284,194
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2078, 55, 1673, 273, 2078, 55, 1673, 18, 1289, 24899, 79, 84, 24, 86, 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, -100, -100 ]
pragma solidity ^0.4.11; /* Copyright 2017 Harry Roberts Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract ERC20TokenInterface { /// @return The total amount of tokens function totalSupply() constant returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant public returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant public returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data); } contract ERC20and223TokenImpl is ERC20TokenInterface { mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; // (ERC20) uint256 internal total_value; function ERC20TokenImpl () internal {} /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } function totalSupply() constant returns (uint256) { return total_value; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { bytes memory empty; return _transfer_internal(msg.sender, _to, _value, false, empty); } function transfer(address _to, uint256 _value, bytes _data) onlyPayloadSize(2 * 32) public returns (bool) { return _transfer_internal(msg.sender, _to, _value, false, _data); } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) { bytes memory empty; return _transfer_internal(_from, _to, _value, true, empty); } function _transfer_internal(address _from, address _to, uint256 _value, bool _dec_allowed, bytes _data) internal returns (bool) { // Verify transaction is possible and not exploitative bool overflow = balanceOf(_to) + _value < balanceOf(_to); if ( balanceOf(_from) < _value || allowance(_from, msg.sender) < _value || overflow ) { return false; } // ERC223 compatibility uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if ( codeLength > 0 ) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value, _data); } // Finally modify balances balances[_from] -= _value; balances[_to] += _value; // only for 'transferFrom', 'transfer' bypasses allowance if( _dec_allowed ) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value,_data); return true; } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } function unapprove(address _spender) public { allowed[msg.sender][_spender] = 0; } function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) { /* * Prevent adjustment of allowed spend unless the value is reset to 0 * Alternatively, call `compareAndApprove` * See: https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM */ // XXX: compatibility problems? if( allowance(msg.sender, _spender) != 0 ) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @param _spender The address to approve /// @param _currentValue The previous value approved, which can be retrieved with allowance(msg.sender, _spender) /// @param _newValue The new value to approve, this will replace the _currentValue /// @return bool Whether the approval was a success (see ERC20's `approve`) function compareAndApprove(address _spender, uint256 _currentValue, uint256 _newValue) onlyPayloadSize(3 * 32) public returns(bool) { if (allowed[msg.sender][_spender] != _currentValue) return false; allowed[msg.sender][_spender] = 0; return approve(_spender, _newValue); } function allowance(address _owner, address _spender) onlyPayloadSize(2 * 32) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract PowTokenBase is ERC20and223TokenImpl { event Mined(address owner, uint256 value); mapping(bytes32 => bool) spends; uint private total_coins; function PowTokenBase() internal {} function () { throw; } function mint(address owner, uint256 value) internal { balances[owner] += value; total_value += value; } /** * A tokens value is proportionate to the chance of finding it using a brute * force search with random inputs. The number of Zero bits, starting at the * beginning, is the metric used to calculate the chance of finding it. * * For example, 0FFFFF... has a difficulty of 4, or 1 in 16. * While 00FFFF... has a difficulty of 8, or 1 in 256 * * difficulty = zerobit_prefix_length * value = 2 ** difficulty * * Each additional zero bit doubles the difficulty, making it take twice as * long for a coin of difficulty 6 to be found compared to a 5. * * The total combined value is a rough estimate of the number of iterations * necessary to find an equal value of tokens. */ function value (bytes32 _coin) constant public returns (uint256) { uint256 idx = 0; uint256 bitcount = 0; while ( idx < 32 ) { uint8 octet = uint8(_coin[idx++]); if ( octet == 0 ) { bitcount += 8; continue; } for ( uint offset = 0; offset < 8; offset++ ) { if( (octet & (1 << offset)) != 0 ) return 2 ** bitcount; bitcount += 1; } } // Somehow _coin is all zeros.. impossible! throw; } function mine_success (bytes32 _coin) internal returns (uint256) { // Only spend coins once if( spends[_coin] == true ) throw; // Success total_coins += 1; spends[_coin] = true; uint256 coin_value = value(_coin); mint(msg.sender, coin_value); Mined(msg.sender, coin_value); return coin_value; } } contract PowTokenHashedBase is PowTokenBase { function PowTokenHashedBase () internal {} function mineFor (address _owner, bytes32 _nonce) public returns (uint256) { return 0; } function mine (bytes32 _nonce) public returns (uint256) { return mineFor(msg.sender, _nonce); } function mineForMany (address[] _owner, bytes32[] _nonce) public returns (uint256) { uint8 N; uint256 result = 0; for( N = 0; N < _nonce.length; N++ ) { result += mineFor(_owner[N], _nonce[N]); } return result; } function mineMany (bytes32[] _nonce) public returns (uint256) { uint8 N; uint256 result = 0; for( N = 0; N < _nonce.length; N++ ) { result += mineFor(msg.sender, _nonce[N]); } return result; } } /** * Implements a Proof of Work token using SHA3 */ contract PowToken_SHA3 is PowTokenHashedBase { string public constant symbol = "PoWS3"; string public constant name = "ProofOfWork SHA3"; uint8 public constant decimals = 12; function mineFor (address _owner, bytes32 _nonce) public returns (uint256) { bytes32 proof_hash = sha3(_owner, _nonce); return mine_success(proof_hash); } } /** * Implements a Proof of Work token using SHA256 */ contract PowToken_SHA256 is PowTokenHashedBase { string public constant symbol = "PoWS2"; string public constant name = "ProofOfWork SHA256"; uint8 public constant decimals = 12; function mineFor (address _owner, bytes32 _nonce) public returns (uint256) { bytes32 proof_hash = sha256(_owner, _nonce); return mine_success(proof_hash); } } contract SaferEcRecover { function SaferEcRecover() internal {} // the following function has been written by Alex Beregszaszi (@axic), // use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } } /** * Implements a Proof of Work token using Elliptic Curves * * Instead of using a hash of `msg.sender` and a `nonce` to calculate the * difficulty it uses an SHA3 hash of the public key from a Bitcoin/Ethereum * compatible secp256k1 elliptic-curve key pair. * * This allows coins to be mined independently of who spends them, but to be * spent the public key must sign the destination `msg.sender`. */ contract PowToken_EC is PowTokenBase, SaferEcRecover { string public constant symbol = "PoWEC"; string public constant name = "ProofOfWork Elliptic Curve"; uint8 public constant decimals = 12; function mineFor (address owner, address coin, uint8 v, bytes32 r, bytes32 s) public returns (uint256) { bool sigok; address verified; bytes32 msg_hash = sha3(owner, coin); // Verify signature matches the expected hash (sigok, verified) = safer_ecrecover(msg_hash, v, r, s); if( ! sigok || coin != verified ) throw; // Extend public key to 256 bits return mine_success(sha3(verified)); } function mine (address coin, uint8 v, bytes32 r, bytes32 s) public returns (uint256) { return mineFor(msg.sender, coin, v, r, s); } function mineForMany (address[] owner, address[] coin, uint8[] v, bytes32[] r, bytes32[] s) public returns (uint256) { uint8 N; uint256 result = 0; for( N = 0; N < coin.length; N++ ) { result += mineFor(owner[N], coin[N], v[N], r[N], s[N]); } return result; } function mineMany (address[] coin, uint8[] v, bytes32[] r, bytes32[] s) public returns (uint256) { uint8 N; uint256 result = 0; for( N = 0; N < coin.length; N++ ) { result += mine(coin[N], v[N], r[N], s[N]); } return result; } }
Verify signature matches the expected hash Extend public key to 256 bits
{ bool sigok; address verified; bytes32 msg_hash = sha3(owner, coin); (sigok, verified) = safer_ecrecover(msg_hash, v, r, s); if( ! sigok || coin != verified ) throw; return mine_success(sha3(verified)); }
12,782,570
[ 1, 8097, 3372, 1885, 326, 2665, 1651, 27686, 1071, 498, 358, 8303, 4125, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 1426, 3553, 601, 31, 203, 3639, 1758, 13808, 31, 203, 3639, 1731, 1578, 1234, 67, 2816, 273, 6056, 23, 12, 8443, 16, 13170, 1769, 203, 203, 3639, 261, 7340, 601, 16, 13808, 13, 273, 7864, 586, 67, 557, 266, 3165, 12, 3576, 67, 2816, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 309, 12, 401, 3553, 601, 747, 13170, 480, 13808, 262, 203, 5411, 604, 31, 203, 203, 3639, 327, 312, 558, 67, 4768, 12, 7819, 23, 12, 19685, 10019, 3639, 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 ]
./full_match/5/0x5B050507373815D825Ba812f92FF31073eab6d4c/sources/contracts/ApeCoinStaking.sol
* @notice Withdraw staked ApeCoin from the ApeCoin pool. If withdraw is total staked amount, performs an automatic claim. @param _amount Amount of ApeCoin/
function withdrawSelfApeCoin(uint256 _amount) external { withdrawApeCoin(_amount, msg.sender); }
1,895,071
[ 1, 1190, 9446, 384, 9477, 432, 347, 27055, 628, 326, 432, 347, 27055, 2845, 18, 225, 971, 598, 9446, 353, 2078, 384, 9477, 3844, 16, 11199, 392, 5859, 7516, 18, 225, 389, 8949, 16811, 434, 432, 347, 27055, 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, 565, 445, 598, 9446, 10084, 37, 347, 27055, 12, 11890, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 598, 9446, 37, 347, 27055, 24899, 8949, 16, 1234, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x9D69045816E4635Ce05135EBeb8567F6e4838E2E/sources/contracts/AirdropERC20.sol
@notice Lets contract-owner set up an airdrop of ERC20 or native tokens to a list of addresses.
function addRecipients(AirdropContent[] calldata _contents) external payable onlyRole(DEFAULT_ADMIN_ROLE) { uint256 len = _contents.length; require(len > 0, "No payees provided."); uint256 currentCount = payeeCount; payeeCount += len; uint256 nativeTokenAmount; for (uint256 i = 0; i < len; ) { airdropContent[i + currentCount] = _contents[i]; if (_contents[i].tokenAddress == CurrencyTransferLib.NATIVE_TOKEN) { nativeTokenAmount += _contents[i].amount; } unchecked { i += 1; } } require(nativeTokenAmount == msg.value, "Incorrect native token amount"); emit RecipientsAdded(currentCount, currentCount + len); }
5,619,639
[ 1, 48, 2413, 6835, 17, 8443, 444, 731, 392, 279, 6909, 1764, 434, 4232, 39, 3462, 578, 6448, 2430, 358, 279, 666, 434, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 22740, 12, 37, 6909, 1764, 1350, 8526, 745, 892, 389, 3980, 13, 3903, 8843, 429, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 3639, 2254, 5034, 562, 273, 389, 3980, 18, 2469, 31, 203, 3639, 2583, 12, 1897, 405, 374, 16, 315, 2279, 8843, 25521, 2112, 1199, 1769, 203, 203, 3639, 2254, 5034, 783, 1380, 273, 8843, 1340, 1380, 31, 203, 3639, 8843, 1340, 1380, 1011, 562, 31, 203, 203, 3639, 2254, 5034, 6448, 1345, 6275, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 562, 31, 262, 288, 203, 5411, 279, 6909, 1764, 1350, 63, 77, 397, 783, 1380, 65, 273, 389, 3980, 63, 77, 15533, 203, 203, 5411, 309, 261, 67, 3980, 63, 77, 8009, 2316, 1887, 422, 13078, 5912, 5664, 18, 50, 12992, 67, 8412, 13, 288, 203, 7734, 6448, 1345, 6275, 1011, 389, 3980, 63, 77, 8009, 8949, 31, 203, 5411, 289, 203, 203, 5411, 22893, 288, 203, 7734, 277, 1011, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2583, 12, 13635, 1345, 6275, 422, 1234, 18, 1132, 16, 315, 16268, 6448, 1147, 3844, 8863, 203, 203, 3639, 3626, 868, 15079, 8602, 12, 2972, 1380, 16, 783, 1380, 397, 562, 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 ]
pragma solidity 0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ 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)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract CostumeToken is PausableToken { using SafeMath for uint256; // Token Details string public constant name = 'Costume Token'; string public constant symbol = 'COST'; uint8 public constant decimals = 18; // 200 Million Total Supply uint256 public constant totalSupply = 200e24; // 120 Million - Supply not for Crowdsale uint256 public initialSupply = 120e24; // 80 Million - Crowdsale limit uint256 public limitCrowdsale = 80e24; // Tokens Distributed - Crowdsale Buyers uint256 public tokensDistributedCrowdsale = 0; // The address of the crowdsale address public crowdsale; // -- MODIFIERS // Modifier, must be called from Crowdsale contract modifier onlyCrowdsale() { require(msg.sender == crowdsale); _; } // Constructor - send initial supply to owner function CostumeToken() public { balances[msg.sender] = initialSupply; } // Set crowdsale address, only by owner // @param - crowdsale address function setCrowdsaleAddress(address _crowdsale) external onlyOwner whenNotPaused { require(crowdsale == address(0)); require(_crowdsale != address(0)); crowdsale = _crowdsale; } // Distribute tokens, only by crowdsale // @param _buyer The buyer address // @param tokens The amount of tokens to send to that address function distributeCrowdsaleTokens(address _buyer, uint tokens) external onlyCrowdsale whenNotPaused { require(_buyer != address(0)); require(tokens > 0); require(tokensDistributedCrowdsale < limitCrowdsale); require(tokensDistributedCrowdsale.add(tokens) <= limitCrowdsale); // Tick up the distributed amount tokensDistributedCrowdsale = tokensDistributedCrowdsale.add(tokens); // Add the funds to buyer address balances[_buyer] = balances[_buyer].add(tokens); } } contract Crowdsale is Pausable { using SafeMath for uint256; // The token being sold CostumeToken public token; // 12.15.2017 - 12:00:00 GMT uint256 public startTime = 1513339200; // 1.31.2018 - 12:00:00 GMT uint256 public endTime = 1517400000; // Costume Wallet address public wallet; // Set tier rates uint256 public rate = 3400; uint256 public rateTier2 = 3200; uint256 public rateTier3 = 3000; uint256 public rateTier4 = 2800; // The maximum amount of wei for each tier // 20 Million Intervals uint256 public limitTier1 = 20e24; uint256 public limitTier2 = 40e24; uint256 public limitTier3 = 60e24; // 80 Million Tokens available for crowdsale uint256 public constant maxTokensRaised = 80e24; // The amount of wei raised uint256 public weiRaised = 0; // The amount of tokens raised uint256 public tokensRaised = 0; // 0.1 ether minumum per contribution uint256 public constant minPurchase = 100 finney; // Crowdsale tokens not purchased bool public remainingTransfered = false; // The number of transactions uint256 public numberOfTransactions; // -- DATA-SETS // Amount each address paid for tokens mapping(address => uint256) public crowdsaleBalances; // Amount of tokens each address received mapping(address => uint256) public tokensBought; // -- EVENTS // Trigger TokenPurchase event event TokenPurchase(address indexed buyer, uint256 value, uint256 amountOfTokens); // Crowdsale Ended event Finalized(); // -- MODIFIERS // Only allow the execution of the function before the crowdsale starts modifier beforeStarting() { require(now < startTime); _; } // Main Constructor // @param _wallet - Fund wallet address // @param _tokenAddress - Associated token address // @param _startTime - Crowdsale start time // @param _endTime - Crowdsale end time function Crowdsale( address _wallet, address _tokenAddress, uint256 _startTime, uint256 _endTime ) public { require(_wallet != address(0)); require(_tokenAddress != address(0)); if (_startTime > 0 && _endTime > 0) { require(_startTime < _endTime); } wallet = _wallet; token = CostumeToken(_tokenAddress); if (_startTime > 0) { startTime = _startTime; } if (_endTime > 0) { endTime = _endTime; } } /// Buy tokens fallback function () external payable { buyTokens(); } /// Buy tokens main function buyTokens() public payable whenNotPaused { require(validPurchase()); uint256 tokens = 0; uint256 amountPaid = adjustAmountValue(); if (tokensRaised < limitTier1) { // Tier 1 tokens = amountPaid.mul(rate); // If the amount of tokens that you want to buy gets out of this tier if (tokensRaised.add(tokens) > limitTier1) { tokens = adjustTokenTierValue(amountPaid, limitTier1, 1, rate); } } else if (tokensRaised >= limitTier1 && tokensRaised < limitTier2) { // Tier 2 tokens = amountPaid.mul(rateTier2); // Breaks tier cap if (tokensRaised.add(tokens) > limitTier2) { tokens = adjustTokenTierValue(amountPaid, limitTier2, 2, rateTier2); } } else if (tokensRaised >= limitTier2 && tokensRaised < limitTier3) { // Tier 3 tokens = amountPaid.mul(rateTier3); // Breaks tier cap if (tokensRaised.add(tokens) > limitTier3) { tokens = adjustTokenTierValue(amountPaid, limitTier3, 3, rateTier3); } } else if (tokensRaised >= limitTier3) { // Tier 4 tokens = amountPaid.mul(rateTier4); } weiRaised = weiRaised.add(amountPaid); tokensRaised = tokensRaised.add(tokens); token.distributeCrowdsaleTokens(msg.sender, tokens); // Keep the records tokensBought[msg.sender] = tokensBought[msg.sender].add(tokens); // Broadcast event TokenPurchase(msg.sender, amountPaid, tokens); // Update records numberOfTransactions = numberOfTransactions.add(1); forwardFunds(amountPaid); } // Forward funds to fund wallet function forwardFunds(uint256 amountPaid) internal whenNotPaused { // Send directly to dev wallet wallet.transfer(amountPaid); } // Adjust wei based on tier, refund if necessaey function adjustAmountValue() internal whenNotPaused returns(uint256) { uint256 amountPaid = msg.value; uint256 differenceWei = 0; // Check final tier if(tokensRaised >= limitTier3) { uint256 addedTokens = tokensRaised.add(amountPaid.mul(rateTier4)); // Have we reached the max? if(addedTokens > maxTokensRaised) { // Find the amount over the max uint256 difference = addedTokens.sub(maxTokensRaised); differenceWei = difference.div(rateTier4); amountPaid = amountPaid.sub(differenceWei); } } // Update balances dataset crowdsaleBalances[msg.sender] = crowdsaleBalances[msg.sender].add(amountPaid); // Transfer at the end if (differenceWei > 0) msg.sender.transfer(differenceWei); return amountPaid; } // Set / change tier rates // @param tier1 - tier4 - Rate per tier function setTierRates(uint256 tier1, uint256 tier2, uint256 tier3, uint256 tier4) external onlyOwner whenNotPaused { require(tier1 > 0 && tier2 > 0 && tier3 > 0 && tier4 > 0); require(tier1 > tier2 && tier2 > tier3 && tier3 > tier4); rate = tier1; rateTier2 = tier2; rateTier3 = tier3; rateTier4 = tier4; } // Adjust token per tier, return wei if necessay // @param amount - Amount buyer paid // @param tokensThisTier - Tokens in tier // @param tierSelected - The current tier // @param _rate - Current rate function adjustTokenTierValue( uint256 amount, uint256 tokensThisTier, uint256 tierSelected, uint256 _rate ) internal returns(uint256 totalTokens) { require(amount > 0 && tokensThisTier > 0 && _rate > 0); require(tierSelected >= 1 && tierSelected <= 4); uint weiThisTier = tokensThisTier.sub(tokensRaised).div(_rate); uint weiNextTier = amount.sub(weiThisTier); uint tokensNextTier = 0; bool returnTokens = false; // If there's excessive wei for the last tier, refund those if(tierSelected != 4) { tokensNextTier = calculateTokensPerTier(weiNextTier, tierSelected.add(1)); } else { returnTokens = true; } totalTokens = tokensThisTier.sub(tokensRaised).add(tokensNextTier); // Do the transfer at the end if (returnTokens) msg.sender.transfer(weiNextTier); } // Return token amount based on wei paid // @param weiPaid - Amount buyer paid // @param tierSelected - The current tier function calculateTokensPerTier(uint256 weiPaid, uint256 tierSelected) internal constant returns(uint256 calculatedTokens) { require(weiPaid > 0); require(tierSelected >= 1 && tierSelected <= 4); if (tierSelected == 1) { calculatedTokens = weiPaid.mul(rate); } else if (tierSelected == 2) { calculatedTokens = weiPaid.mul(rateTier2); } else if (tierSelected == 3) { calculatedTokens = weiPaid.mul(rateTier3); } else { calculatedTokens = weiPaid.mul(rateTier4); } } // Confirm valid purchase function validPurchase() internal constant returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value > 0; bool withinTokenLimit = tokensRaised < maxTokensRaised; bool minimumPurchase = msg.value >= minPurchase; return withinPeriod && nonZeroPurchase && withinTokenLimit && minimumPurchase; } // Check if sale ended function hasEnded() public constant returns(bool) { return now > endTime || tokensRaised >= maxTokensRaised; } // Finalize if ended function completeCrowdsale() external onlyOwner whenNotPaused { require(hasEnded()); // Transfer left over tokens transferTokensLeftOver(); // Call finalized event Finalized(); } // Transfer any remaining tokens from Crowdsale function transferTokensLeftOver() internal { require(!remainingTransfered); require(maxTokensRaised > tokensRaised); remainingTransfered = true; uint256 remainingTokens = maxTokensRaised.sub(tokensRaised); token.distributeCrowdsaleTokens(msg.sender, remainingTokens); } // Change dates before crowdsale has started // @param _startTime - New start time // @param _endTime - New end time function changeDates(uint256 _startTime, uint256 _endTime) external onlyOwner beforeStarting { if (_startTime > 0 && _endTime > 0) { require(_startTime < _endTime); } if (_startTime > 0) { startTime = _startTime; } if (_endTime > 0) { endTime = _endTime; } } // Change the end date // @param _endTime - New end time function changeEndDate(uint256 _endTime) external onlyOwner { require(_endTime > startTime); require(_endTime > now); require(!hasEnded()); if (_endTime > 0) { endTime = _endTime; } } }
Buy tokens main Tier 1 If the amount of tokens that you want to buy gets out of this tier Breaks tier cap Breaks tier cap
function buyTokens() public payable whenNotPaused { require(validPurchase()); uint256 tokens = 0; uint256 amountPaid = adjustAmountValue(); if (tokensRaised < limitTier1) { tokens = amountPaid.mul(rate); if (tokensRaised.add(tokens) > limitTier1) { tokens = adjustTokenTierValue(amountPaid, limitTier1, 1, rate); } if (tokensRaised.add(tokens) > limitTier2) { tokens = adjustTokenTierValue(amountPaid, limitTier2, 2, rateTier2); } if (tokensRaised.add(tokens) > limitTier3) { tokens = adjustTokenTierValue(amountPaid, limitTier3, 3, rateTier3); } } weiRaised = weiRaised.add(amountPaid); tokensRaised = tokensRaised.add(tokens); token.distributeCrowdsaleTokens(msg.sender, tokens); forwardFunds(amountPaid); }
12,790,728
[ 1, 38, 9835, 2430, 2774, 399, 2453, 404, 971, 326, 3844, 434, 2430, 716, 1846, 2545, 358, 30143, 5571, 596, 434, 333, 17742, 17030, 87, 17742, 3523, 17030, 87, 17742, 3523, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 445, 30143, 5157, 1435, 1071, 8843, 429, 1347, 1248, 28590, 288, 203, 1377, 2583, 12, 877, 23164, 10663, 203, 203, 1377, 2254, 5034, 2430, 273, 374, 31, 203, 1377, 2254, 5034, 3844, 16507, 350, 273, 5765, 6275, 620, 5621, 203, 203, 1377, 309, 261, 7860, 12649, 5918, 411, 1800, 15671, 21, 13, 288, 203, 203, 540, 2430, 273, 3844, 16507, 350, 18, 16411, 12, 5141, 1769, 203, 203, 540, 309, 261, 7860, 12649, 5918, 18, 1289, 12, 7860, 13, 405, 1800, 15671, 21, 13, 288, 203, 203, 5411, 2430, 273, 5765, 1345, 15671, 620, 12, 8949, 16507, 350, 16, 1800, 15671, 21, 16, 404, 16, 4993, 1769, 203, 540, 289, 203, 203, 203, 203, 540, 309, 261, 7860, 12649, 5918, 18, 1289, 12, 7860, 13, 405, 1800, 15671, 22, 13, 288, 203, 5411, 2430, 273, 5765, 1345, 15671, 620, 12, 8949, 16507, 350, 16, 1800, 15671, 22, 16, 576, 16, 4993, 15671, 22, 1769, 203, 540, 289, 203, 203, 203, 203, 540, 309, 261, 7860, 12649, 5918, 18, 1289, 12, 7860, 13, 405, 1800, 15671, 23, 13, 288, 203, 5411, 2430, 273, 5765, 1345, 15671, 620, 12, 8949, 16507, 350, 16, 1800, 15671, 23, 16, 890, 16, 4993, 15671, 23, 1769, 203, 540, 289, 203, 203, 203, 203, 1377, 289, 203, 203, 1377, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 1289, 12, 8949, 16507, 350, 1769, 203, 1377, 2430, 12649, 5918, 273, 2430, 12649, 5918, 18, 1289, 12, 7860, 1769, 203, 1377, 1147, 18, 2251, 887, 39, 492, 2377, 5349, 2 ]
pragma solidity >=0.4.22 <0.6.0; import "./Cuts.sol"; import "./Cell.sol"; import "./Layers.sol"; import "./helperFunctions.sol"; import "./GoldCrush.sol"; import "./auction.sol"; import "./SafeMath.sol"; import "./heavyEquipment.sol"; import "./ClaimLocationManager.sol"; contract GoldClaim is helperFunctions, Cuts, mine { ClaimLocationManager clmanager; ClaimLocationManager.location locationObject; int x; int y; using SafeMath for uint; uint numberOfOwners; bool faucetIsHot; uint previousFaucet; address auctionHouseAddress; Auction auctionHouse; address creator; string public nameOfTheClaim; bool forSale; int locationOnTheMapX; int LocationOnTheMapY; // xy map bool prospected; uint internal previousRandom; uint internal nonceCounter; uint id; //number of claim address owner; uint totalGoldFound; uint totalPaydirt; uint totalCutsOnTheClaim; mapping(address => bool) owners; address[] allOwners; //all old and new owners mapping(address => uint) ownerNumber; uint goldFound; address[] coOwners; mapping(address => bool) isCoOwner; Cuts[] cuts; uint maxCuts; uint[] objectsOnTheClaim; // uint[] objectsInStorage; //also on the claim uint maxObjectsPossible; // hangar size; constructor (address _creator, string memory name, address auctionhouse, address clm) public payable { //creator should be auction house? creator = _creator; clmanager = ClaimLocationManager(clm); forSale = true; nameOfTheClaim = name; auctionHouseAddress = auctionhouse; auctionHouse = Auction(auctionHouseAddress); numberOfOwners = 0; //fire event? } modifier OnlyOwner () { require(msg.sender == owner); _; } modifier PaidOption () { require( msg.value >= 1 ether); _; } function getAddress () public view returns (address) { return address(this); } function prospectGoldClaim () public payable PaidOption returns (uint) { //needed to reveal amount of cuts possible. Advised to do this before you buy the claim. require(!prospected); totalCutsOnTheClaim = 1 + random(id + msg.value + block.number + (uint160(address(this))) + now)%10; prospected = true; // for(uint i=0; i < totalCutsOnTheClaim; i++) { // Cut activecut = Cut(address); return (totalCutsOnTheClaim); } function getLocationX() public view returns (int) { return locationObject.x; } function getLocationY() public view returns (int) { return locationObject.y; } function getLocationId () public view returns (uint) { return locationObject.locationId; } function createCut() public payable OnlyOwner { //create the actual prospected cuts require(prospected); require(totalCutsOnTheClaim > 0); //should be the same as prospected require(cutsArray.length == 0); uint max = 10; //should not be needed setOwnerOfClaim(owner); while((cutsArray.length < totalCutsOnTheClaim) && ( max > 0)){ createNewCutNow(); max--; } } function getIdOfClaim() public view returns (uint) { return id; } function getName () public view returns (string memory) { return nameOfTheClaim; } function setName (string memory name) public payable returns (string memory) { nameOfTheClaim = name; return nameOfTheClaim; } function checkForSale() public view returns (bool) { return forSale; } function setForSale (bool status) public returns (bool) { forSale = status; return forSale; } function getOwner () public view returns (address) { return owner; } function setOwner (address newOwner) public { //not public ofc! public for testing //need modifier so auction house can change owner // clear all old owners when claim gets new owners. // to do , co-owners for(uint i=0;i < allOwners.length;i++) { address temp = allOwners[i]; owners[temp] = false; deleteOwner(temp); } allOwners.push(newOwner); owner = newOwner; // GoldCrush gc = GoldCrush(creator); setOwnerOfClaim(newOwner); ownerNumber[owner] = numberOfOwners; } function getTotalCutsOnClaim () public view returns (uint) { return totalCutsOnTheClaim; } function getOwnerOfClaim () public view returns (address) { return owner; } function mine (uint layer, uint x, uint y) public { } function deleteOwner (address owner) public OnlyOwner { uint index =ownerNumber[owner]; allOwners[index] = allOwners[allOwners.length-1]; } function setClaimLocationManager (address adres) public { clmanager = ClaimLocationManager(adres); } function getLocationObjectAttached() public returns(uint) { uint idOftheObject = clmanager.bindClaimToLocation(address(this)); int x = clmanager.getX(idOftheObject); int y = clmanager.getY(idOftheObject); locationObject.locationId = idOftheObject; locationObject.x = x; locationObject.y = y; locationObject.claim = address(this); return idOftheObject; } }
all old and new owners
address[] allOwners;
6,485,507
[ 1, 454, 1592, 471, 394, 25937, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 8526, 777, 5460, 414, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xeb48F8e09fcEa950de0d9f7C91ebefcd5Bc5d08C/sources/contracts/rand.sol
Specific to Koven Oracle
keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
7,161,354
[ 1, 9969, 358, 1475, 1527, 275, 28544, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 498, 2310, 273, 374, 92, 22, 329, 20, 3030, 70, 23, 73, 27, 8313, 18212, 22, 22343, 7598, 5193, 74, 378, 15613, 2539, 7950, 69, 29, 74, 22, 1403, 71, 9349, 6669, 8313, 26, 28946, 507, 10525, 73, 7329, 24, 71, 3437, 2499, 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 ]
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract Balance is Ownable { using EnumerableSet for EnumerableSet.AddressSet; /// @notice Maximum inspector count. uint256 public constant MAXIMUM_INSPECTOR_COUNT = 100; /// @notice Maximum consumer count. uint256 public constant MAXIMUM_CONSUMER_COUNT = 100; /// @notice Maximum accept or reject claims by one call. uint256 public constant MAXIMUM_CLAIM_PACKAGE = 500; /// @notice Treasury contract address payable public treasury; /// @dev Inspectors list. EnumerableSet.AddressSet internal _inspectors; /// @dev Consumers list. EnumerableSet.AddressSet internal _consumers; /// @notice Account balance. mapping(address => uint256) public balanceOf; /// @notice Account claim. mapping(address => uint256) public claimOf; /// @notice Possible statuses that a bill may be in. enum BillStatus { Pending, Accepted, Rejected } struct Bill { // Identificator. uint256 id; // Claimant. address claimant; // Target account. address account; // Claim gas fee. uint256 gasFee; // Claim protocol fee. uint256 protocolFee; // Current bill status. BillStatus status; } /// @notice Bills. mapping(uint256 => Bill) public bills; /// @notice Bill count. uint256 public billCount; event TreasuryChanged(address indexed treasury); event InspectorAdded(address indexed inspector); event InspectorRemoved(address indexed inspector); event ConsumerAdded(address indexed consumer); event ConsumerRemoved(address indexed consumer); event Deposit(address indexed recipient, uint256 amount); event Refund(address indexed recipient, uint256 amount); event Claim(address indexed account, uint256 indexed bill, string description); event AcceptClaim(uint256 indexed bill); event RejectClaim(uint256 indexed bill); constructor(address payable _treasury) { treasury = _treasury; } modifier onlyInspector() { require(_inspectors.contains(_msgSender()), "Balance: caller is not the inspector"); _; } /** * @notice Change treasury contract address. * @param _treasury New treasury contract address. */ function changeTreasury(address payable _treasury) external onlyOwner { treasury = _treasury; emit TreasuryChanged(treasury); } /** * @notice Add inspector. * @param inspector Added inspector. */ function addInspector(address inspector) external onlyOwner { require(!_inspectors.contains(inspector), "Balance::addInspector: inspector already added"); require( _inspectors.length() < MAXIMUM_INSPECTOR_COUNT, "Balance::addInspector: inspector must not exceed maximum count" ); _inspectors.add(inspector); emit InspectorAdded(inspector); } /** * @notice Remove inspector. * @param inspector Removed inspector. */ function removeInspector(address inspector) external onlyOwner { require(_inspectors.contains(inspector), "Balance::removeInspector: inspector already removed"); _inspectors.remove(inspector); emit InspectorRemoved(inspector); } /** * @notice Get all inspectors. * @return All inspectors addresses. */ function inspectors() external view returns (address[] memory) { address[] memory result = new address[](_inspectors.length()); for (uint256 i = 0; i < _inspectors.length(); i++) { result[i] = _inspectors.at(i); } return result; } /** * @notice Add consumer. * @param consumer Added consumer. */ function addConsumer(address consumer) external onlyOwner { require(!_consumers.contains(consumer), "Balance::addConsumer: consumer already added"); require( _consumers.length() < MAXIMUM_CONSUMER_COUNT, "Balance::addConsumer: consumer must not exceed maximum count" ); _consumers.add(consumer); emit ConsumerAdded(consumer); } /** * @notice Remove consumer. * @param consumer Removed consumer. */ function removeConsumer(address consumer) external onlyOwner { require(_consumers.contains(consumer), "Balance::removeConsumer: consumer already removed"); _consumers.remove(consumer); emit ConsumerRemoved(consumer); } /** * @notice Get all consumers. * @return All consumers addresses. */ function consumers() external view returns (address[] memory) { address[] memory result = new address[](_consumers.length()); for (uint256 i = 0; i < _consumers.length(); i++) { result[i] = _consumers.at(i); } return result; } /** * @notice Get net balance of account. * @param account Target account. * @return Net balance (balance minus claim). */ function netBalanceOf(address account) public view returns (uint256) { return balanceOf[account] - claimOf[account]; } /** * @notice Deposit ETH to balance. * @param recipient Target recipient. */ function deposit(address recipient) external payable { require(recipient != address(0), "Balance::deposit: invalid recipient"); require(msg.value > 0, "Balance::deposit: negative or zero deposit"); balanceOf[recipient] += msg.value; emit Deposit(recipient, msg.value); } /** * @notice Refund ETH from balance. * @param amount Refunded amount. */ function refund(uint256 amount) external { address payable recipient = payable(_msgSender()); require(amount > 0, "Balance::refund: negative or zero refund"); require(amount <= netBalanceOf(recipient), "Balance::refund: refund amount exceeds net balance"); balanceOf[recipient] -= amount; recipient.transfer(amount); emit Refund(recipient, amount); } /** * @notice Send claim. * @param account Target account. * @param gasFee Claim gas fee. * @param protocolFee Claim protocol fee. * @param description Claim description. */ function claim( address account, uint256 gasFee, uint256 protocolFee, string memory description ) external returns (uint256) { require( // solhint-disable-next-line avoid-tx-origin tx.origin == account || _consumers.contains(tx.origin), "Balance: caller is not a consumer" ); uint256 amount = gasFee + protocolFee; require(amount > 0, "Balance::claim: negative or zero claim"); require(amount <= netBalanceOf(account), "Balance::claim: claim amount exceeds net balance"); claimOf[account] += amount; billCount++; bills[billCount] = Bill(billCount, _msgSender(), account, gasFee, protocolFee, BillStatus.Pending); emit Claim(account, billCount, description); return billCount; } /** * @notice Accept bills package. * @param _bills Target bills. * @param gasFees Confirmed claims gas fees by bills. * @param protocolFees Confirmed claims protocol fees by bills. */ function acceptClaims( uint256[] memory _bills, uint256[] memory gasFees, uint256[] memory protocolFees ) external onlyInspector { require( _bills.length == gasFees.length && _bills.length == protocolFees.length, "Balance::acceptClaims: arity mismatch" ); require(_bills.length <= MAXIMUM_CLAIM_PACKAGE, "Balance::acceptClaims: too many claims"); uint256 transferredAmount; for (uint256 i = 0; i < _bills.length; i++) { uint256 billId = _bills[i]; require(billId > 0 && billId <= billCount, "Balance::acceptClaims: bill not found"); uint256 gasFee = gasFees[i]; uint256 protocolFee = protocolFees[i]; uint256 amount = gasFee + protocolFee; Bill storage bill = bills[billId]; uint256 claimAmount = bill.gasFee + bill.protocolFee; require(bill.status == BillStatus.Pending, "Balance::acceptClaims: bill already processed"); require(amount <= claimAmount, "Balance::acceptClaims: claim amount exceeds max fee"); bill.status = BillStatus.Accepted; bill.gasFee = gasFee; bill.protocolFee = protocolFee; claimOf[bill.account] -= claimAmount; balanceOf[bill.account] -= amount; transferredAmount += amount; emit AcceptClaim(bill.id); } treasury.transfer(transferredAmount); } /** * @notice Reject bills package. * @param _bills Target bills. */ function rejectClaims(uint256[] memory _bills) external onlyInspector { require(_bills.length < MAXIMUM_CLAIM_PACKAGE, "Balance::rejectClaims: too many claims"); for (uint256 i = 0; i < _bills.length; i++) { uint256 billId = _bills[i]; require(billId > 0 && billId <= billCount, "Balance::rejectClaims: bill not found"); Bill storage bill = bills[billId]; require(bill.status == BillStatus.Pending, "Balance::rejectClaims: bill already processed"); uint256 amount = bill.gasFee + bill.protocolFee; bill.status = BillStatus.Rejected; claimOf[bill.account] -= amount; emit RejectClaim(bill.id); } } }
* @notice Add inspector. @param inspector Added inspector./
function addInspector(address inspector) external onlyOwner { require(!_inspectors.contains(inspector), "Balance::addInspector: inspector already added"); require( _inspectors.length() < MAXIMUM_INSPECTOR_COUNT, "Balance::addInspector: inspector must not exceed maximum count" ); _inspectors.add(inspector); emit InspectorAdded(inspector); }
7,264,397
[ 1, 986, 22700, 18, 225, 22700, 25808, 22700, 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, 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, 225, 445, 527, 19443, 12, 2867, 22700, 13, 3903, 1338, 5541, 288, 203, 565, 2583, 12, 5, 67, 12009, 1383, 18, 12298, 12, 12009, 280, 3631, 315, 13937, 2866, 1289, 19443, 30, 22700, 1818, 3096, 8863, 203, 565, 2583, 12, 203, 1377, 389, 12009, 1383, 18, 2469, 1435, 411, 4552, 18605, 67, 706, 23810, 22727, 67, 7240, 16, 203, 1377, 315, 13937, 2866, 1289, 19443, 30, 22700, 1297, 486, 9943, 4207, 1056, 6, 203, 565, 11272, 203, 203, 565, 389, 12009, 1383, 18, 1289, 12, 12009, 280, 1769, 203, 203, 565, 3626, 31965, 8602, 12, 12009, 280, 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 ]
pragma solidity ^0.4.23; contract God { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyProfitsHolders() { require(myDividends(true) > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onInjectEtherFromIco(uint _incomingEthereum, uint _dividends, uint profitPerShare_); event onInjectEtherToDividend(address sender, uint _incomingEthereum, uint profitPerShare_); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "God"; string public symbol = "God"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; uint constant internal MIN_TOKEN_TRANSFER = 1e10; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => mapping(address => uint256)) internal allowed; // administrator list (see above on what they can do) address internal owner; mapping(address => bool) public administrators; address bankAddress; mapping(address => bool) public contractAddresses; int internal contractPayout = 0; bool internal isProjectBonus = true; uint internal projectBonus = 0; uint internal projectBonusRate = 10; // 1/10 /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor() public { // add administrators here owner = msg.sender; administrators[owner] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() public payable { purchaseTokens(msg.value, 0x0); } function injectEtherFromIco() public payable { uint _incomingEthereum = msg.value; require(_incomingEthereum > 0); uint256 _dividends = SafeMath.div(_incomingEthereum, dividendFee_); if (isProjectBonus) { uint temp = SafeMath.div(_dividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); emit onInjectEtherFromIco(_incomingEthereum, _dividends, profitPerShare_); } function injectEtherToDividend() public payable { uint _incomingEthereum = msg.value; require(_incomingEthereum > 0); profitPerShare_ += (_incomingEthereum * magnitude / (tokenSupply_)); emit onInjectEtherToDividend(msg.sender, _incomingEthereum, profitPerShare_); } function injectEther() public payable {} /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyProfitsHolders() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyProfitsHolders() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyTokenHolders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); if (isProjectBonus) { uint temp = SafeMath.div(_dividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders() public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); bytes memory empty; transferFromInternal(_customerAddress, _toAddress, _amountOfTokens, empty); return true; } function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data) internal { require(_toAddress != address(0x0)); uint fromLength; uint toLength; assembly { fromLength := extcodesize(_from) toLength := extcodesize(_toAddress) } if (fromLength > 0 && toLength <= 0) { // contract to human contractAddresses[_from] = true; contractPayout -= (int) (_amountOfTokens); tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); } else if (fromLength <= 0 && toLength > 0) { // human to contract contractAddresses[_toAddress] = true; contractPayout += (int) (_amountOfTokens); tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens); payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens); } else if (fromLength > 0 && toLength > 0) { // contract to contract contractAddresses[_from] = true; contractAddresses[_toAddress] = true; } else { // human to human payoutsTo_[_from] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); } // exchange tokens tokenBalanceLedger_[_from] = SafeMath.sub(tokenBalanceLedger_[_from], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // to contract if (toLength > 0) { ERC223Receiving receiver = ERC223Receiving(_toAddress); receiver.tokenFallback(_from, _amountOfTokens, _data); } // fire event emit Transfer(_from, _toAddress, _amountOfTokens); } function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns (bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); // Good old ERC20. return true; } function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data) public { if (_from != msg.sender) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_from] && _amountOfTokens <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); } else { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= tokenBalanceLedger_[_from]); } transferFromInternal(_from, _to, _amountOfTokens, _data); } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ function setBank(address _identifier, uint256 value) onlyAdministrator() public { bankAddress = _identifier; contractAddresses[_identifier] = true; tokenBalanceLedger_[_identifier] = value; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { require(_identifier != owner); administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function getContractPayout() onlyAdministrator() public view returns (int) { return contractPayout; } function getIsProjectBonus() onlyAdministrator() public view returns (bool) { return isProjectBonus; } function setIsProjectBonus(bool value) onlyAdministrator() public { isProjectBonus = value; } function getProjectBonus() onlyAdministrator() public view returns (uint) { return projectBonus; } function takeProjectBonus(address to, uint value) onlyAdministrator() public { require(value <= projectBonus); to.transfer(value); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns (uint256) { return tokenSupply_; } // erc 20 function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return getBalance(_customerAddress); } function getProfitPerShare() public view returns (uint256) { return (uint256) ((int256)(tokenSupply_*profitPerShare_)) / magnitude; } function getContractETH() public view returns (uint256) { return address(this).balance; } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns (uint256) { if(contractAddresses[_customerAddress]){ return 0; } return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the token balance of any single address. */ function getBalance(address _customerAddress) view public returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns (uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); if (isProjectBonus) { uint temp = SafeMath.div(_undividedDividends, projectBonusRate); _dividends = SafeMath.sub(_dividends, temp); projectBonus = SafeMath.add(projectBonus, temp); } uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + (((tokenPriceIncremental_) ** 2) * (tokenSupply_ ** 2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } contract ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
* Calculate token sell value. It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code./ underflow attempts BTFO
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; }
6,305,784
[ 1, 8695, 1147, 357, 80, 460, 18, 2597, 1807, 392, 4886, 16, 27370, 4095, 732, 314, 836, 1846, 326, 600, 305, 881, 7294, 598, 518, 316, 888, 1979, 1507, 12155, 31, 10548, 22586, 7841, 358, 5309, 6970, 1334, 578, 3613, 24190, 342, 9391, 87, 316, 18035, 560, 981, 18, 19, 3613, 2426, 7531, 605, 56, 3313, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2430, 774, 41, 18664, 379, 67, 12, 11890, 5034, 389, 7860, 13, 203, 565, 2713, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 203, 3639, 2254, 5034, 2430, 67, 273, 261, 67, 7860, 397, 404, 73, 2643, 1769, 203, 3639, 2254, 5034, 389, 2316, 3088, 1283, 273, 261, 2316, 3088, 1283, 67, 397, 404, 73, 2643, 1769, 203, 3639, 2254, 5034, 389, 2437, 8872, 273, 203, 3639, 261, 203, 3639, 14060, 10477, 18, 1717, 12, 203, 5411, 261, 203, 5411, 261, 203, 5411, 261, 203, 5411, 1147, 5147, 4435, 67, 397, 261, 2316, 5147, 10798, 287, 67, 380, 261, 67, 2316, 3088, 1283, 342, 404, 73, 2643, 3719, 203, 5411, 262, 300, 1147, 5147, 10798, 287, 67, 203, 5411, 262, 380, 261, 7860, 67, 300, 404, 73, 2643, 13, 203, 5411, 262, 16, 261, 2316, 5147, 10798, 287, 67, 380, 14015, 7860, 67, 2826, 576, 300, 2430, 67, 13, 342, 404, 73, 2643, 3719, 342, 576, 203, 3639, 262, 203, 3639, 342, 404, 73, 2643, 1769, 203, 3639, 327, 389, 2437, 8872, 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 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {GnosisAuction} from "../../libraries/GnosisAuction.sol"; import { RibbonThetaVaultStorage } from "../../storage/RibbonThetaVaultStorage.sol"; import {Vault} from "../../libraries/Vault.sol"; import {VaultLifecycle} from "../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../libraries/ShareMath.sol"; import {RibbonVault} from "./base/RibbonVault.sol"; /** * UPGRADEABILITY: Since we use the upgradeable proxy pattern, we must observe * the inheritance chain closely. * Any changes/appends in storage variable needs to happen in RibbonThetaVaultStorage. * RibbonThetaVault should not inherit from any other contract aside from RibbonVault, RibbonThetaVaultStorage */ contract RibbonThetaVault is RibbonVault, RibbonThetaVaultStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice oTokenFactory is the factory contract used to spawn otokens. Used to lookup otokens. address public immutable OTOKEN_FACTORY; // The minimum duration for an option auction. uint256 private constant MIN_AUCTION_DURATION = 1 hours; /************************************************ * EVENTS ***********************************************/ event OpenShort( address indexed options, uint256 depositAmount, address indexed manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address indexed manager ); event NewOptionStrikeSelected(uint256 strikePrice, uint256 delta); event PremiumDiscountSet( uint256 premiumDiscount, uint256 newPremiumDiscount ); event AuctionDurationSet( uint256 auctionDuration, uint256 newAuctionDuration ); event InstantWithdraw( address indexed account, uint256 amount, uint256 round ); /************************************************ * STRUCTS ***********************************************/ /** * @notice Initialization parameters for the vault. * @param _owner is the owner of the vault with critical permissions * @param _feeRecipient is the address to recieve vault performance and management fees * @param _managementFee is the management fee pct. * @param _performanceFee is the perfomance fee pct. * @param _tokenName is the name of the token * @param _tokenSymbol is the symbol of the token * @param _optionsPremiumPricer is the address of the contract with the black-scholes premium calculation logic * @param _strikeSelection is the address of the contract with strike selection logic * @param _premiumDiscount is the vault's discount applied to the premium * @param _auctionDuration is the duration of the gnosis auction * @param _isUsdcAuction is whether Gnosis auction should be denominated in USDC * @param _swapPath is the path for swapping */ struct InitParams { address _owner; address _keeper; address _feeRecipient; uint256 _managementFee; uint256 _performanceFee; string _tokenName; string _tokenSymbol; address _optionsPremiumPricer; address _strikeSelection; uint32 _premiumDiscount; uint256 _auctionDuration; bool _isUsdcAuction; bytes _swapPath; } /************************************************ * CONSTRUCTOR & INITIALIZATION ***********************************************/ /** * @notice Initializes the contract with immutable variables * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _oTokenFactory is the contract address for minting new opyn option types (strikes, asset, expiry) * @param _gammaController is the contract address for opyn actions * @param _marginPool is the contract address for providing collateral to opyn * @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions * @param _uniswapRouter is the contract address of UniswapV3 router that handles swaps * @param _uniswapFactory is the contract address of UniswapV3 factory containing */ constructor( address _weth, address _usdc, address _oTokenFactory, address _gammaController, address _marginPool, address _gnosisEasyAuction, address _uniswapRouter, address _uniswapFactory ) RibbonVault( _weth, _usdc, _gammaController, _marginPool, _gnosisEasyAuction, _uniswapRouter, _uniswapFactory ) { require(_oTokenFactory != address(0), "!_oTokenFactory"); OTOKEN_FACTORY = _oTokenFactory; } /** * @notice Initializes the OptionVault contract with storage variables. * @param _initParams is the struct with vault initialization parameters * @param _vaultParams is the struct with vault general data */ function initialize( InitParams calldata _initParams, Vault.VaultParams calldata _vaultParams ) external initializer { baseInitialize( _initParams._owner, _initParams._keeper, _initParams._feeRecipient, _initParams._managementFee, _initParams._performanceFee, _initParams._tokenName, _initParams._tokenSymbol, _vaultParams ); require( _initParams._optionsPremiumPricer != address(0), "!_optionsPremiumPricer" ); require( _initParams._strikeSelection != address(0), "!_strikeSelection" ); require( _initParams._premiumDiscount > 0 && _initParams._premiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER, "!_premiumDiscount" ); require( _initParams._auctionDuration >= MIN_AUCTION_DURATION, "!_auctionDuration" ); optionsPremiumPricer = _initParams._optionsPremiumPricer; strikeSelection = _initParams._strikeSelection; premiumDiscount = _initParams._premiumDiscount; auctionDuration = _initParams._auctionDuration; isUsdcAuction = _initParams._isUsdcAuction; if (_initParams._isUsdcAuction) { require(_checkPath(_initParams._swapPath), "Invalid swapPath"); swapPath = _initParams._swapPath; } } /************************************************ * SETTERS ***********************************************/ /** * @notice Sets the new discount on premiums for options we are selling * @param newPremiumDiscount is the premium discount */ function setPremiumDiscount(uint256 newPremiumDiscount) external onlyOwner { require( newPremiumDiscount > 0 && newPremiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER, "Invalid discount" ); emit PremiumDiscountSet(premiumDiscount, newPremiumDiscount); premiumDiscount = newPremiumDiscount; } /** * @notice Sets the new auction duration * @param newAuctionDuration is the auction duration */ function setAuctionDuration(uint256 newAuctionDuration) external onlyOwner { require( newAuctionDuration >= MIN_AUCTION_DURATION, "Invalid auction duration" ); emit AuctionDurationSet(auctionDuration, newAuctionDuration); auctionDuration = newAuctionDuration; } /** * @notice Sets the new strike selection contract * @param newStrikeSelection is the address of the new strike selection contract */ function setStrikeSelection(address newStrikeSelection) external onlyOwner { require(newStrikeSelection != address(0), "!newStrikeSelection"); strikeSelection = newStrikeSelection; } /** * @notice Sets the new options premium pricer contract * @param newOptionsPremiumPricer is the address of the new strike selection contract */ function setOptionsPremiumPricer(address newOptionsPremiumPricer) external onlyOwner { require( newOptionsPremiumPricer != address(0), "!newOptionsPremiumPricer" ); optionsPremiumPricer = newOptionsPremiumPricer; } /** * @notice Optionality to set strike price manually * @param strikePrice is the strike price of the new oTokens (decimals = 8) */ function setStrikePrice(uint128 strikePrice) external onlyOwner nonReentrant { require(strikePrice > 0, "!strikePrice"); overriddenStrikePrice = strikePrice; lastStrikeOverrideRound = vaultState.round; } /** * @notice Sets a new path for swaps * @param newSwapPath is the new path */ function setSwapPath(bytes calldata newSwapPath) external onlyOwner nonReentrant { require(isUsdcAuction, "!isUsdcAuction"); require(_checkPath(newSwapPath), "Invalid swapPath"); swapPath = newSwapPath; } /************************************************ * VAULT OPERATIONS ***********************************************/ /** * @notice Withdraws the assets on the vault using the outstanding `DepositReceipt.amount` * @param amount is the amount to withdraw */ function withdrawInstantly(uint256 amount) external nonReentrant { Vault.DepositReceipt storage depositReceipt = depositReceipts[msg.sender]; uint256 currentRound = vaultState.round; require(amount > 0, "!amount"); require(depositReceipt.round == currentRound, "Invalid round"); uint256 receiptAmount = depositReceipt.amount; require(receiptAmount >= amount, "Exceed amount"); // Subtraction underflow checks already ensure it is smaller than uint104 depositReceipt.amount = uint104(receiptAmount.sub(amount)); vaultState.totalPending = uint128( uint256(vaultState.totalPending).sub(amount) ); emit InstantWithdraw(msg.sender, amount, currentRound); transferAsset(msg.sender, amount); } /** * @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round */ function completeWithdraw() external nonReentrant { uint256 withdrawAmount = _completeWithdraw(); lastQueuedWithdrawAmount = uint128( uint256(lastQueuedWithdrawAmount).sub(withdrawAmount) ); } /** * @notice Sets the next option the vault will be shorting, and closes the existing short. * This allows all the users to withdraw if the next option is malicious. */ function commitAndClose() external nonReentrant { address oldOption = optionState.currentOption; VaultLifecycle.CloseParams memory closeParams = VaultLifecycle.CloseParams({ OTOKEN_FACTORY: OTOKEN_FACTORY, USDC: USDC, currentOption: oldOption, delay: DELAY, lastStrikeOverrideRound: lastStrikeOverrideRound, overriddenStrikePrice: overriddenStrikePrice }); ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) = VaultLifecycle.commitAndClose( strikeSelection, optionsPremiumPricer, premiumDiscount, closeParams, vaultParams, vaultState ); emit NewOptionStrikeSelected(strikePrice, delta); ShareMath.assertUint104(premium); currentOtokenPremium = uint104(premium); optionState.nextOption = otokenAddress; uint256 nextOptionReady = block.timestamp.add(DELAY); require( nextOptionReady <= type(uint32).max, "Overflow nextOptionReady" ); optionState.nextOptionReadyAt = uint32(nextOptionReady); _closeShort(oldOption); } /** * @notice Closes the existing short position for the vault. */ function _closeShort(address oldOption) private { uint256 lockedAmount = vaultState.lockedAmount; if (oldOption != address(0)) { vaultState.lastLockedAmount = uint104(lockedAmount); } vaultState.lockedAmount = 0; optionState.currentOption = address(0); if (oldOption != address(0)) { uint256 withdrawAmount = VaultLifecycle.settleShort(GAMMA_CONTROLLER); emit CloseShort(oldOption, withdrawAmount, msg.sender); } } /** * @notice Rolls the vault's funds into a new short position. */ function rollToNextOption() external onlyKeeper nonReentrant { ( address newOption, uint256 lockedBalance, uint256 queuedWithdrawAmount ) = _rollToNextOption(uint256(lastQueuedWithdrawAmount)); lastQueuedWithdrawAmount = queuedWithdrawAmount; ShareMath.assertUint104(lockedBalance); vaultState.lockedAmount = uint104(lockedBalance); emit OpenShort(newOption, lockedBalance, msg.sender); VaultLifecycle.createShort( GAMMA_CONTROLLER, MARGIN_POOL, newOption, lockedBalance ); _startAuction(); } /** * @notice Initiate the gnosis auction. */ function startAuction() external onlyKeeper nonReentrant { _startAuction(); } function _startAuction() private { GnosisAuction.AuctionDetails memory auctionDetails; uint256 currOtokenPremium = currentOtokenPremium; require(currOtokenPremium > 0, "!currentOtokenPremium"); bool _isUsdcAuction = isUsdcAuction; auctionDetails.oTokenAddress = optionState.currentOption; auctionDetails.gnosisEasyAuction = GNOSIS_EASY_AUCTION; auctionDetails.asset = _isUsdcAuction ? USDC : vaultParams.asset; auctionDetails.assetDecimals = _isUsdcAuction ? 6 : vaultParams.decimals; auctionDetails.oTokenPremium = currOtokenPremium; auctionDetails.duration = auctionDuration; optionAuctionID = VaultLifecycle.startAuction(auctionDetails); } /** * @notice Burn the remaining oTokens left over from gnosis auction. */ function burnRemainingOTokens() external onlyKeeper nonReentrant { uint256 unlockedAssetAmount = VaultLifecycle.burnOtokens( GAMMA_CONTROLLER, optionState.currentOption ); vaultState.lockedAmount = uint104( uint256(vaultState.lockedAmount).sub(unlockedAssetAmount) ); } /** * @notice Settle USDC auction and swap the proceeds to underlying asset * @param minAmountOut is the minimum amount of underlying acceptable for the swap */ function settleAuctionAndSwap(uint256 minAmountOut) external onlyKeeper nonReentrant { require(isUsdcAuction, "!isUsdcAuction"); require(minAmountOut > 0, "!minAmountOut"); VaultLifecycle.settleAuction(GNOSIS_EASY_AUCTION, optionAuctionID); VaultLifecycle.swap(USDC, minAmountOut, UNISWAP_ROUTER, swapPath); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the 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.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {DSMath} from "../vendor/DSMath.sol"; import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol"; import {IOtoken} from "../interfaces/GammaInterface.sol"; import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol"; import {Vault} from "./Vault.sol"; import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol"; library GnosisAuction { using SafeMath for uint256; using SafeERC20 for IERC20; event InitiateGnosisAuction( address indexed auctioningToken, address indexed biddingToken, uint256 auctionCounter, address indexed manager ); event PlaceAuctionBid( uint256 auctionId, address indexed auctioningToken, uint256 sellAmount, uint256 buyAmount, address indexed bidder ); struct AuctionDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 oTokenPremium; uint256 duration; } struct BidDetails { address oTokenAddress; address gnosisEasyAuction; address asset; uint256 assetDecimals; uint256 auctionId; uint256 lockedBalance; uint256 optionAllocation; uint256 optionPremium; address bidder; } function startAuction(AuctionDetails calldata auctionDetails) internal returns (uint256 auctionID) { uint256 oTokenSellAmount = getOTokenSellAmount(auctionDetails.oTokenAddress); IERC20(auctionDetails.oTokenAddress).safeApprove( auctionDetails.gnosisEasyAuction, IERC20(auctionDetails.oTokenAddress).balanceOf(address(this)) ); // minBidAmount is total oTokens to sell * premium per oToken // shift decimals to correspond to decimals of USDC for puts // and underlying for calls uint256 minBidAmount = DSMath .wmul( oTokenSellAmount.mul(10**10), auctionDetails .oTokenPremium ) .div(10**(uint256(18).sub(auctionDetails.assetDecimals))); require( minBidAmount <= type(uint96).max, "optionPremium * oTokenSellAmount > type(uint96) max value!" ); uint256 auctionEnd = block.timestamp.add(auctionDetails.duration); auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction) .initiateAuction( // address of oToken we minted and are selling auctionDetails.oTokenAddress, // address of asset we want in exchange for oTokens. Should match vault `asset` auctionDetails.asset, // orders can be cancelled at any time during the auction auctionEnd, // order will last for `duration` auctionEnd, // we are selling all of the otokens minus a fee taken by gnosis uint96(oTokenSellAmount), // the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price uint96(minBidAmount), // the minimum bidding amount must be 1 * 10 ** -assetDecimals 1, // the min funding threshold 0, // no atomic closure false, // access manager contract address(0), // bytes for storing info like a whitelist for who can bid bytes("") ); emit InitiateGnosisAuction( auctionDetails.oTokenAddress, auctionDetails.asset, auctionID, msg.sender ); } function placeBid(BidDetails calldata bidDetails) internal returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { // calculate how much to allocate sellAmount = bidDetails .lockedBalance .mul(bidDetails.optionAllocation) .div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER); // divide the `asset` sellAmount by the target premium per oToken to // get the number of oTokens to buy (8 decimals) buyAmount = sellAmount .mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS))) .div(bidDetails.optionPremium) .div(10**bidDetails.assetDecimals); require( sellAmount <= type(uint96).max, "sellAmount > type(uint96) max value!" ); require( buyAmount <= type(uint96).max, "buyAmount > type(uint96) max value!" ); // approve that amount IERC20(bidDetails.asset).safeApprove( bidDetails.gnosisEasyAuction, sellAmount ); uint96[] memory _minBuyAmounts = new uint96[](1); uint96[] memory _sellAmounts = new uint96[](1); bytes32[] memory _prevSellOrders = new bytes32[](1); _minBuyAmounts[0] = uint96(buyAmount); _sellAmounts[0] = uint96(sellAmount); _prevSellOrders[ 0 ] = 0x0000000000000000000000000000000000000000000000000000000000000001; // place sell order with that amount userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders( bidDetails.auctionId, _minBuyAmounts, _sellAmounts, _prevSellOrders, "0x" ); emit PlaceAuctionBid( bidDetails.auctionId, bidDetails.oTokenAddress, sellAmount, buyAmount, bidDetails.bidder ); return (sellAmount, buyAmount, userId); } function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) internal { bytes32 order = encodeOrder( auctionSellOrder.userId, auctionSellOrder.buyAmount, auctionSellOrder.sellAmount ); bytes32[] memory orders = new bytes32[](1); orders[0] = order; IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder( IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(), orders ); } function getOTokenSellAmount(address oTokenAddress) internal view returns (uint256) { // We take our current oToken balance. That will be our sell amount // but otokens will be transferred to gnosis. uint256 oTokenSellAmount = IERC20(oTokenAddress).balanceOf(address(this)); require( oTokenSellAmount <= type(uint96).max, "oTokenSellAmount > type(uint96) max value!" ); return oTokenSellAmount; } function getOTokenPremium( address oTokenAddress, address optionsPremiumPricer, uint256 premiumDiscount ) internal view returns (uint256) { IOtoken newOToken = IOtoken(oTokenAddress); IOptionsPremiumPricer premiumPricer = IOptionsPremiumPricer(optionsPremiumPricer); // Apply black-scholes formula (from rvol library) to option given its features // and get price for 100 contracts denominated in the underlying asset for call option // and USDC for put option uint256 optionPremium = premiumPricer.getPremium( newOToken.strikePrice(), newOToken.expiryTimestamp(), newOToken.isPut() ); // Apply a discount to incentivize arbitraguers optionPremium = optionPremium.mul(premiumDiscount).div( 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER ); require( optionPremium <= type(uint96).max, "optionPremium > type(uint96) max value!" ); return optionPremium; } function encodeOrder( uint64 userId, uint96 buyAmount, uint96 sellAmount ) internal pure returns (bytes32) { return bytes32( (uint256(userId) << 192) + (uint256(buyAmount) << 96) + uint256(sellAmount) ); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; abstract contract RibbonThetaVaultStorageV1 { // Logic contract used to price options address public optionsPremiumPricer; // Logic contract used to select strike prices address public strikeSelection; // Premium discount on options we are selling (thousandths place: 000 - 999) uint256 public premiumDiscount; // Current oToken premium uint256 public currentOtokenPremium; // Last round id at which the strike was manually overridden uint16 public lastStrikeOverrideRound; // Price last overridden strike set to uint256 public overriddenStrikePrice; // Auction duration uint256 public auctionDuration; // Auction id of current option uint256 public optionAuctionID; } abstract contract RibbonThetaVaultStorageV2 { // Amount locked for scheduled withdrawals last week; uint256 public lastQueuedWithdrawAmount; } abstract contract RibbonThetaVaultStorageV3 { // Auction will be denominated in USDC if true bool public isUsdcAuction; // Path for swaps bytes public swapPath; } // We are following Compound's method of upgrading new contract implementations // When we need to add new storage variables, we create a new version of RibbonThetaVaultStorage // e.g. RibbonThetaVaultStorage<versionNumber>, so finally it would look like // contract RibbonThetaVaultStorage is RibbonThetaVaultStorageV1, RibbonThetaVaultStorageV2 abstract contract RibbonThetaVaultStorage is RibbonThetaVaultStorageV1, RibbonThetaVaultStorageV2, RibbonThetaVaultStorageV3 { } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library Vault { /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ // Fees are 6-decimal places. For example: 20 * 10**6 = 20% uint256 internal constant FEE_MULTIPLIER = 10**6; // Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount. uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10; // Otokens have 8 decimal places. uint256 internal constant OTOKEN_DECIMALS = 8; // Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10% uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2; // Placeholder uint value to prevent cold writes uint256 internal constant PLACEHOLDER_UINT = 1; struct VaultParams { // Option type the vault is selling bool isPut; // Token decimals for vault shares uint8 decimals; // Asset used in Theta / Delta Vault address asset; // Underlying asset of the options sold by vault address underlying; // Minimum supply of the vault shares issued, for ETH it's 10**10 uint56 minimumSupply; // Vault cap uint104 cap; } struct OptionState { // Option that the vault is shorting / longing in the next cycle address nextOption; // Option that the vault is currently shorting / longing address currentOption; // The timestamp when the `nextOption` can be used by the vault uint32 nextOptionReadyAt; } struct VaultState { // 32 byte slot 1 // Current round number. `round` represents the number of `period`s elapsed. uint16 round; // Amount that is currently locked for selling options uint104 lockedAmount; // Amount that was locked for selling options in the previous round // used for calculating performance fee deduction uint104 lastLockedAmount; // 32 byte slot 2 // Stores the total tally of how much of `asset` there is // to be used to mint rTHETA tokens uint128 totalPending; // Amount locked for scheduled withdrawals; uint128 queuedWithdrawShares; } struct DepositReceipt { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit uint104 amount; // Unredeemed shares balance uint128 unredeemedShares; } struct Withdrawal { // Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years. uint16 round; // Number of shares withdrawn uint128 shares; } struct AuctionSellOrder { // Amount of `asset` token offered in auction uint96 sellAmount; // Amount of oToken requested in auction uint96 buyAmount; // User Id of delta vault in latest gnosis auction uint64 userId; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Vault} from "./Vault.sol"; import {ShareMath} from "./ShareMath.sol"; import {IStrikeSelection} from "../interfaces/IRibbon.sol"; import {GnosisAuction} from "./GnosisAuction.sol"; import { IOtokenFactory, IOtoken, IController, GammaTypes } from "../interfaces/GammaInterface.sol"; import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol"; import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol"; import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol"; import {UniswapRouter} from "./UniswapRouter.sol"; library VaultLifecycle { using SafeMath for uint256; using SupportsNonCompliantERC20 for IERC20; struct CloseParams { address OTOKEN_FACTORY; address USDC; address currentOption; uint256 delay; uint16 lastStrikeOverrideRound; uint256 overriddenStrikePrice; } /** * @notice Sets the next option the vault will be shorting, and calculates its premium for the auction * @param strikeSelection is the address of the contract with strike selection logic * @param optionsPremiumPricer is the address of the contract with the black-scholes premium calculation logic * @param premiumDiscount is the vault's discount applied to the premium * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param vaultState is the struct with vault accounting state * @return otokenAddress is the address of the new option * @return premium is the premium of the new option * @return strikePrice is the strike price of the new option * @return delta is the delta of the new option */ function commitAndClose( address strikeSelection, address optionsPremiumPricer, uint256 premiumDiscount, CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, Vault.VaultState storage vaultState ) external returns ( address otokenAddress, uint256 premium, uint256 strikePrice, uint256 delta ) { uint256 expiry; // uninitialized state if (closeParams.currentOption == address(0)) { expiry = getNextFriday(block.timestamp); } else { expiry = getNextFriday( IOtoken(closeParams.currentOption).expiryTimestamp() ); } IStrikeSelection selection = IStrikeSelection(strikeSelection); bool isPut = vaultParams.isPut; address underlying = vaultParams.underlying; address asset = vaultParams.asset; (strikePrice, delta) = closeParams.lastStrikeOverrideRound == vaultState.round ? (closeParams.overriddenStrikePrice, selection.delta()) : selection.getStrikePrice(expiry, isPut); require(strikePrice != 0, "!strikePrice"); // retrieve address if option already exists, or deploy it otokenAddress = getOrDeployOtoken( closeParams, vaultParams, underlying, asset, strikePrice, expiry, isPut ); // get the black scholes premium of the option premium = GnosisAuction.getOTokenPremium( otokenAddress, optionsPremiumPricer, premiumDiscount ); require(premium > 0, "!premium"); return (otokenAddress, premium, strikePrice, delta); } /** * @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes * @param otokenAddress is the address of the otoken * @param vaultParams is the struct with vault general data * @param collateralAsset is the address of the collateral asset * @param USDC is the address of usdc * @param delay is the delay between commitAndClose and rollToNextOption */ function verifyOtoken( address otokenAddress, Vault.VaultParams storage vaultParams, address collateralAsset, address USDC, uint256 delay ) private view { require(otokenAddress != address(0), "!otokenAddress"); IOtoken otoken = IOtoken(otokenAddress); require(otoken.isPut() == vaultParams.isPut, "Type mismatch"); require( otoken.underlyingAsset() == vaultParams.underlying, "Wrong underlyingAsset" ); require( otoken.collateralAsset() == collateralAsset, "Wrong collateralAsset" ); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay"); } /** * @param currentShareSupply is the supply of the shares invoked with totalSupply() * @param asset is the address of the vault's asset * @param decimals is the decimals of the asset * @param lastQueuedWithdrawAmount is the amount queued for withdrawals from last round * @param performanceFee is the perf fee percent to charge on premiums * @param managementFee is the management fee percent to charge on the AUM */ struct RolloverParams { uint256 decimals; uint256 totalBalance; uint256 currentShareSupply; uint256 lastQueuedWithdrawAmount; uint256 performanceFee; uint256 managementFee; } /** * @notice Calculate the shares to mint, new price per share, and amount of funds to re-allocate as collateral for the new round * @param vaultState is the storage variable vaultState passed from RibbonVault * @param params is the rollover parameters passed to compute the next state * @return newLockedAmount is the amount of funds to allocate for the new round * @return queuedWithdrawAmount is the amount of funds set aside for withdrawal * @return newPricePerShare is the price per share of the new round * @return mintShares is the amount of shares to mint from deposits * @return performanceFeeInAsset is the performance fee charged by vault * @return totalVaultFee is the total amount of fee charged by vault */ function rollover( Vault.VaultState storage vaultState, RolloverParams calldata params ) external view returns ( uint256 newLockedAmount, uint256 queuedWithdrawAmount, uint256 newPricePerShare, uint256 mintShares, uint256 performanceFeeInAsset, uint256 totalVaultFee ) { uint256 currentBalance = params.totalBalance; uint256 pendingAmount = vaultState.totalPending; uint256 queuedWithdrawShares = vaultState.queuedWithdrawShares; uint256 balanceForVaultFees; { uint256 pricePerShareBeforeFee = ShareMath.pricePerShare( params.currentShareSupply, currentBalance, pendingAmount, params.decimals ); uint256 queuedWithdrawBeforeFee = params.currentShareSupply > 0 ? ShareMath.sharesToAsset( queuedWithdrawShares, pricePerShareBeforeFee, params.decimals ) : 0; // Deduct the difference between the newly scheduled withdrawals // and the older withdrawals // so we can charge them fees before they leave uint256 withdrawAmountDiff = queuedWithdrawBeforeFee > params.lastQueuedWithdrawAmount ? queuedWithdrawBeforeFee.sub( params.lastQueuedWithdrawAmount ) : 0; balanceForVaultFees = currentBalance .sub(queuedWithdrawBeforeFee) .add(withdrawAmountDiff); } { (performanceFeeInAsset, , totalVaultFee) = VaultLifecycle .getVaultFees( balanceForVaultFees, vaultState.lastLockedAmount, vaultState.totalPending, params.performanceFee, params.managementFee ); } // Take into account the fee // so we can calculate the newPricePerShare currentBalance = currentBalance.sub(totalVaultFee); { newPricePerShare = ShareMath.pricePerShare( params.currentShareSupply, currentBalance, pendingAmount, params.decimals ); // After closing the short, if the options expire in-the-money // vault pricePerShare would go down because vault's asset balance decreased. // This ensures that the newly-minted shares do not take on the loss. mintShares = ShareMath.assetToShares( pendingAmount, newPricePerShare, params.decimals ); uint256 newSupply = params.currentShareSupply.add(mintShares); queuedWithdrawAmount = newSupply > 0 ? ShareMath.sharesToAsset( queuedWithdrawShares, newPricePerShare, params.decimals ) : 0; } return ( currentBalance.sub(queuedWithdrawAmount), // new locked balance subtracts the queued withdrawals queuedWithdrawAmount, newPricePerShare, mintShares, performanceFeeInAsset, totalVaultFee ); } /** * @notice Creates the actual Opyn short position by depositing collateral and minting otokens * @param gammaController is the address of the opyn controller contract * @param marginPool is the address of the opyn margin contract which holds the collateral * @param oTokenAddress is the address of the otoken to mint * @param depositAmount is the amount of collateral to deposit * @return the otoken mint amount */ function createShort( address gammaController, address marginPool, address oTokenAddress, uint256 depositAmount ) external returns (uint256) { IController controller = IController(gammaController); uint256 newVaultID = (controller.getAccountVaultCounter(address(this))).add(1); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IOtoken oToken = IOtoken(oTokenAddress); address collateralAsset = oToken.collateralAsset(); uint256 collateralDecimals = uint256(IERC20Detailed(collateralAsset).decimals()); uint256 mintAmount; if (oToken.isPut()) { // For minting puts, there will be instances where the full depositAmount will not be used for minting. // This is because of an issue with precision. // // For ETH put options, we are calculating the mintAmount (10**8 decimals) using // the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down. // As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens. // // For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens. // We retain the dust in the vault so the calling contract can withdraw the // actual locked amount + dust at settlement. // // To test this behavior, we can console.log // MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault) // to see how much dust (or excess collateral) is left behind. mintAmount = depositAmount .mul(10**Vault.OTOKEN_DECIMALS) .mul(10**18) // we use 10**18 to give extra precision .div(oToken.strikePrice().mul(10**(10 + collateralDecimals))); } else { mintAmount = depositAmount; if (collateralDecimals > 8) { uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals if (mintAmount > scaleBy) { mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8 } } } // double approve to fix non-compliant ERC20s IERC20 collateralToken = IERC20(collateralAsset); collateralToken.safeApproveNonCompliant(marginPool, depositAmount); IController.ActionArgs[] memory actions = new IController.ActionArgs[](3); actions[0] = IController.ActionArgs( IController.ActionType.OpenVault, address(this), // owner address(this), // receiver address(0), // asset, otoken newVaultID, // vaultId 0, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.DepositCollateral, address(this), // owner address(this), // address to transfer from collateralAsset, // deposited asset newVaultID, // vaultId depositAmount, // amount 0, //index "" //data ); actions[2] = IController.ActionArgs( IController.ActionType.MintShortOption, address(this), // owner address(this), // address to transfer to oTokenAddress, // option address newVaultID, // vaultId mintAmount, // amount 0, //index "" //data ); controller.operate(actions); return mintAmount; } /** * @notice Close the existing short otoken position. Currently this implementation is simple. * It closes the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by calling SettleVault action, this assumption should hold. * @param gammaController is the address of the opyn controller contract * @return amount of collateral redeemed from the vault */ function settleShort(address gammaController) external returns (uint256) { IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); // An otoken's collateralAsset is the vault's `asset` // So in the context of performing Opyn short operations we call them collateralAsset IERC20 collateralToken = IERC20(vault.collateralAssets[0]); // The short position has been previously closed, or all the otokens have been burned. // So we return early. if (address(collateralToken) == address(0)) { return 0; } // This is equivalent to doing IERC20(vault.asset).balanceOf(address(this)) uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // If it is after expiry, we need to settle the short position using the normal way // Delete the vault and withdraw all remaining collateral from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.SettleVault, address(this), // owner address(this), // address to transfer to address(0), // not used vaultID, // vaultId 0, // not used 0, // not used "" // not used ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple. * It calls the `Redeem` action to claim the payout. * @param gammaController is the address of the opyn controller contract * @param oldOption is the address of the old option * @param asset is the address of the vault's asset * @return amount of asset received by exercising the option */ function settleLong( address gammaController, address oldOption, address asset ) external returns (uint256) { IController controller = IController(gammaController); uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this)); if (controller.getPayout(oldOption, oldOptionBalance) == 0) { return 0; } uint256 startAssetBalance = IERC20(asset).balanceOf(address(this)); // If it is after expiry, we need to redeem the profits IController.ActionArgs[] memory actions = new IController.ActionArgs[](1); actions[0] = IController.ActionArgs( IController.ActionType.Redeem, address(0), // not used address(this), // address to send profits to oldOption, // address of otoken 0, // not used oldOptionBalance, // otoken balance 0, // not used "" // not used ); controller.operate(actions); uint256 endAssetBalance = IERC20(asset).balanceOf(address(this)); return endAssetBalance.sub(startAssetBalance); } /** * @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple. * It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will * only have a single vault open at any given time. * @param gammaController is the address of the opyn controller contract * @param currentOption is the address of the current option * @return amount of collateral redeemed by burning otokens */ function burnOtokens(address gammaController, address currentOption) external returns (uint256) { uint256 numOTokensToBurn = IERC20(currentOption).balanceOf(address(this)); require(numOTokensToBurn > 0, "No oTokens to burn"); IController controller = IController(gammaController); // gets the currently active vault ID uint256 vaultID = controller.getAccountVaultCounter(address(this)); GammaTypes.Vault memory vault = controller.getVault(address(this), vaultID); require(vault.shortOtokens.length > 0, "No short"); IERC20 collateralToken = IERC20(vault.collateralAssets[0]); uint256 startCollateralBalance = collateralToken.balanceOf(address(this)); // Burning `amount` of oTokens from the ribbon vault, // then withdrawing the corresponding collateral amount from the vault IController.ActionArgs[] memory actions = new IController.ActionArgs[](2); actions[0] = IController.ActionArgs( IController.ActionType.BurnShortOption, address(this), // owner address(this), // address to transfer from address(vault.shortOtokens[0]), // otoken address vaultID, // vaultId numOTokensToBurn, // amount 0, //index "" //data ); actions[1] = IController.ActionArgs( IController.ActionType.WithdrawCollateral, address(this), // owner address(this), // address to transfer to address(collateralToken), // withdrawn asset vaultID, // vaultId vault.collateralAmounts[0].mul(numOTokensToBurn).div( vault.shortAmounts[0] ), // amount 0, //index "" //data ); controller.operate(actions); uint256 endCollateralBalance = collateralToken.balanceOf(address(this)); return endCollateralBalance.sub(startCollateralBalance); } /** * @notice Calculates the performance and management fee for this week's round * @param currentBalance is the balance of funds held on the vault after closing short * @param lastLockedAmount is the amount of funds locked from the previous round * @param pendingAmount is the pending deposit amount * @param performanceFeePercent is the performance fee pct. * @param managementFeePercent is the management fee pct. * @return performanceFeeInAsset is the performance fee * @return managementFeeInAsset is the management fee * @return vaultFee is the total fees */ function getVaultFees( uint256 currentBalance, uint256 lastLockedAmount, uint256 pendingAmount, uint256 performanceFeePercent, uint256 managementFeePercent ) internal pure returns ( uint256 performanceFeeInAsset, uint256 managementFeeInAsset, uint256 vaultFee ) { // At the first round, currentBalance=0, pendingAmount>0 // so we just do not charge anything on the first round uint256 lockedBalanceSansPending = currentBalance > pendingAmount ? currentBalance.sub(pendingAmount) : 0; uint256 _performanceFeeInAsset; uint256 _managementFeeInAsset; uint256 _vaultFee; // Take performance fee and management fee ONLY if difference between // last week and this week's vault deposits, taking into account pending // deposits and withdrawals, is positive. If it is negative, last week's // option expired ITM past breakeven, and the vault took a loss so we // do not collect performance fee for last week if (lockedBalanceSansPending > lastLockedAmount) { _performanceFeeInAsset = performanceFeePercent > 0 ? lockedBalanceSansPending .sub(lastLockedAmount) .mul(performanceFeePercent) .div(100 * Vault.FEE_MULTIPLIER) : 0; _managementFeeInAsset = managementFeePercent > 0 ? lockedBalanceSansPending.mul(managementFeePercent).div( 100 * Vault.FEE_MULTIPLIER ) : 0; _vaultFee = _performanceFeeInAsset.add(_managementFeeInAsset); } return (_performanceFeeInAsset, _managementFeeInAsset, _vaultFee); } /** * @notice Either retrieves the option token if it already exists, or deploy it * @param closeParams is the struct with details on previous option and strike selection details * @param vaultParams is the struct with vault general data * @param underlying is the address of the underlying asset of the option * @param collateralAsset is the address of the collateral asset of the option * @param strikePrice is the strike price of the option * @param expiry is the expiry timestamp of the option * @param isPut is whether the option is a put * @return the address of the option */ function getOrDeployOtoken( CloseParams calldata closeParams, Vault.VaultParams storage vaultParams, address underlying, address collateralAsset, uint256 strikePrice, uint256 expiry, bool isPut ) internal returns (address) { IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY); address otokenFromFactory = factory.getOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); if (otokenFromFactory != address(0)) { return otokenFromFactory; } address otoken = factory.createOtoken( underlying, closeParams.USDC, collateralAsset, strikePrice, expiry, isPut ); verifyOtoken( otoken, vaultParams, collateralAsset, closeParams.USDC, closeParams.delay ); return otoken; } /** * @notice Starts the gnosis auction * @param auctionDetails is the struct with all the custom parameters of the auction * @return the auction id of the newly created auction */ function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails) external returns (uint256) { return GnosisAuction.startAuction(auctionDetails); } /** * @notice Settles the gnosis auction * @param gnosisEasyAuction is the contract address of Gnosis easy auction protocol * @param auctionID is the auction ID of the gnosis easy auction */ function settleAuction(address gnosisEasyAuction, uint256 auctionID) internal { IGnosisAuction(gnosisEasyAuction).settleAuction(auctionID); } /** * @notice Swaps tokens using UniswapV3 router * @param tokenIn is the token address to swap * @param minAmountOut is the minimum acceptable amount of tokenOut received from swap * @param router is the contract address of UniswapV3 router * @param swapPath is the swap path e.g. encodePacked(tokenIn, poolFee, tokenOut) */ function swap( address tokenIn, uint256 minAmountOut, address router, bytes calldata swapPath ) external { uint256 balance = IERC20(tokenIn).balanceOf(address(this)); if (balance > 0) { UniswapRouter.swap( address(this), tokenIn, balance, minAmountOut, router, swapPath ); } } function checkPath( bytes calldata swapPath, address validTokenIn, address validTokenOut, address uniswapFactory ) external view returns (bool isValidPath) { return UniswapRouter.checkPath( swapPath, validTokenIn, validTokenOut, uniswapFactory ); } /** * @notice Places a bid in an auction * @param bidDetails is the struct with all the details of the bid including the auction's id and how much to bid */ function placeBid(GnosisAuction.BidDetails calldata bidDetails) external returns ( uint256 sellAmount, uint256 buyAmount, uint64 userId ) { return GnosisAuction.placeBid(bidDetails); } /** * @notice Claims the oTokens belonging to the vault * @param auctionSellOrder is the sell order of the bid * @param gnosisEasyAuction is the address of the gnosis auction contract holding custody to the funds * @param counterpartyThetaVault is the address of the counterparty theta vault of this delta vault */ function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault ) external { GnosisAuction.claimAuctionOtokens( auctionSellOrder, gnosisEasyAuction, counterpartyThetaVault ); } /** * @notice Verify the constructor params satisfy requirements * @param owner is the owner of the vault with critical permissions * @param feeRecipient is the address to recieve vault performance and management fees * @param performanceFee is the perfomance fee pct. * @param tokenName is the name of the token * @param tokenSymbol is the symbol of the token * @param _vaultParams is the struct with vault general data */ function verifyInitializerParams( address owner, address keeper, address feeRecipient, uint256 performanceFee, uint256 managementFee, string calldata tokenName, string calldata tokenSymbol, Vault.VaultParams calldata _vaultParams ) external pure { require(owner != address(0), "!owner"); require(keeper != address(0), "!keeper"); require(feeRecipient != address(0), "!feeRecipient"); require( performanceFee < 100 * Vault.FEE_MULTIPLIER, "performanceFee >= 100%" ); require( managementFee < 100 * Vault.FEE_MULTIPLIER, "managementFee >= 100%" ); require(bytes(tokenName).length > 0, "!tokenName"); require(bytes(tokenSymbol).length > 0, "!tokenSymbol"); require(_vaultParams.asset != address(0), "!asset"); require(_vaultParams.underlying != address(0), "!underlying"); require(_vaultParams.minimumSupply > 0, "!minimumSupply"); require(_vaultParams.cap > 0, "!cap"); require( _vaultParams.cap > _vaultParams.minimumSupply, "cap has to be higher than minimumSupply" ); } /** * @notice Gets the next options expiry timestamp * @param currentExpiry is the expiry timestamp of the current option * Reference: https://codereview.stackexchange.com/a/33532 * Examples: * getNextFriday(week 1 thursday) -> week 1 friday * getNextFriday(week 1 friday) -> week 2 friday * getNextFriday(week 1 saturday) -> week 2 friday */ function getNextFriday(uint256 currentExpiry) internal pure returns (uint256) { // dayOfWeek = 0 (sunday) - 6 (saturday) uint256 dayOfWeek = ((currentExpiry / 1 days) + 4) % 7; uint256 nextFriday = currentExpiry + ((7 + 5 - dayOfWeek) % 7) * 1 days; uint256 friday8am = nextFriday - (nextFriday % (24 hours)) + (8 hours); // If the passed currentExpiry is day=Friday hour>8am, we simply increment it by a week to next Friday if (currentExpiry >= friday8am) { friday8am += 7 days; } return friday8am; } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {Vault} from "./Vault.sol"; library ShareMath { using SafeMath for uint256; uint256 internal constant PLACEHOLDER_UINT = 1; function assetToShares( uint256 assetAmount, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return assetAmount.mul(10**decimals).div(assetPerShare); } function sharesToAsset( uint256 shares, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256) { // If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet // which should never happen. // Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes. require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare"); return shares.mul(assetPerShare).div(10**decimals); } /** * @notice Returns the shares unredeemed by the user given their DepositReceipt * @param depositReceipt is the user's deposit receipt * @param currentRound is the `round` stored on the vault * @param assetPerShare is the price in asset per share * @param decimals is the number of decimals the asset/shares use * @return unredeemedShares is the user's virtual balance of shares that are owed */ function getSharesFromReceipt( Vault.DepositReceipt memory depositReceipt, uint256 currentRound, uint256 assetPerShare, uint256 decimals ) internal pure returns (uint256 unredeemedShares) { if (depositReceipt.round > 0 && depositReceipt.round < currentRound) { uint256 sharesFromRound = assetToShares(depositReceipt.amount, assetPerShare, decimals); return uint256(depositReceipt.unredeemedShares).add(sharesFromRound); } return depositReceipt.unredeemedShares; } function pricePerShare( uint256 totalSupply, uint256 totalBalance, uint256 pendingAmount, uint256 decimals ) internal pure returns (uint256) { uint256 singleShare = 10**decimals; return totalSupply > 0 ? singleShare.mul(totalBalance.sub(pendingAmount)).div( totalSupply ) : singleShare; } /************************************************ * HELPERS ***********************************************/ function assertUint104(uint256 num) internal pure { require(num <= type(uint104).max, "Overflow uint104"); } function assertUint128(uint256 num) internal pure { require(num <= type(uint128).max, "Overflow uint128"); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {Vault} from "../../../libraries/Vault.sol"; import {VaultLifecycle} from "../../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../../libraries/ShareMath.sol"; import {IWETH} from "../../../interfaces/IWETH.sol"; contract RibbonVault is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; /************************************************ * NON UPGRADEABLE STORAGE ***********************************************/ /// @notice Stores the user's pending deposit for the round mapping(address => Vault.DepositReceipt) public depositReceipts; /// @notice On every round's close, the pricePerShare value of an rTHETA token is stored /// This is used to determine the number of shares to be returned /// to a user with their DepositReceipt.depositAmount mapping(uint256 => uint256) public roundPricePerShare; /// @notice Stores pending user withdrawals mapping(address => Vault.Withdrawal) public withdrawals; /// @notice Vault's parameters like cap, decimals Vault.VaultParams public vaultParams; /// @notice Vault's lifecycle state like round and locked amounts Vault.VaultState public vaultState; /// @notice Vault's state of the options sold and the timelocked option Vault.OptionState public optionState; /// @notice Fee recipient for the performance and management fees address public feeRecipient; /// @notice role in charge of weekly vault operations such as rollToNextOption and burnRemainingOTokens // no access to critical vault changes address public keeper; /// @notice Performance fee charged on premiums earned in rollToNextOption. Only charged when there is no loss. uint256 public performanceFee; /// @notice Management fee charged on entire AUM in rollToNextOption. Only charged when there is no loss. uint256 public managementFee; // Gap is left to avoid storage collisions. Though RibbonVault is not upgradeable, we add this as a safety measure. uint256[30] private ____gap; // *IMPORTANT* NO NEW STORAGE VARIABLES SHOULD BE ADDED HERE // This is to prevent storage collisions. All storage variables should be appended to RibbonThetaVaultStorage // or RibbonDeltaVaultStorage instead. Read this documentation to learn more: // https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice WETH9 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 address public immutable WETH; /// @notice USDC 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 address public immutable USDC; /// @notice 15 minute timelock between commitAndClose and rollToNexOption. uint256 public constant DELAY = 15 minutes; /// @notice 7 day period between each options sale. uint256 public constant PERIOD = 7 days; // Number of weeks per year = 52.142857 weeks * FEE_MULTIPLIER = 52142857 // Dividing by weeks per year requires doing num.mul(FEE_MULTIPLIER).div(WEEKS_PER_YEAR) uint256 private constant WEEKS_PER_YEAR = 52142857; // GAMMA_CONTROLLER is the top-level contract in Gamma protocol // which allows users to perform multiple actions on their vaults // and positions https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/Controller.sol address public immutable GAMMA_CONTROLLER; // MARGIN_POOL is Gamma protocol's collateral pool. // Needed to approve collateral.safeTransferFrom for minting otokens. // https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/MarginPool.sol address public immutable MARGIN_POOL; // GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids // https://github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol address public immutable GNOSIS_EASY_AUCTION; // UNISWAP_ROUTER is the contract address of UniswapV3 Router which handles swaps // https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISwapRouter.sol address public immutable UNISWAP_ROUTER; // UNISWAP_FACTORY is the contract address of UniswapV3 Factory which stores pool information // https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/IUniswapV3Factory.sol address public immutable UNISWAP_FACTORY; /************************************************ * EVENTS ***********************************************/ event Deposit(address indexed account, uint256 amount, uint256 round); event InitiateWithdraw( address indexed account, uint256 shares, uint256 round ); event Redeem(address indexed account, uint256 share, uint256 round); event ManagementFeeSet(uint256 managementFee, uint256 newManagementFee); event PerformanceFeeSet(uint256 performanceFee, uint256 newPerformanceFee); event CapSet(uint256 oldCap, uint256 newCap); event Withdraw(address indexed account, uint256 amount, uint256 shares); event CollectVaultFees( uint256 performanceFee, uint256 vaultFee, uint256 round, address indexed feeRecipient ); /************************************************ * CONSTRUCTOR & INITIALIZATION ***********************************************/ /** * @notice Initializes the contract with immutable variables * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _gammaController is the contract address for opyn actions * @param _marginPool is the contract address for providing collateral to opyn * @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions * @param _uniswapRouter is the contract address for UniswapV3 router which handles swaps * @param _uniswapFactory is the contract address for UniswapV3 factory */ constructor( address _weth, address _usdc, address _gammaController, address _marginPool, address _gnosisEasyAuction, address _uniswapRouter, address _uniswapFactory ) { require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_gnosisEasyAuction != address(0), "!_gnosisEasyAuction"); require(_gammaController != address(0), "!_gammaController"); require(_marginPool != address(0), "!_marginPool"); require(_uniswapRouter != address(0), "!_uniswapRouter"); require(_uniswapFactory != address(0), "!_uniswapFactory"); WETH = _weth; USDC = _usdc; GAMMA_CONTROLLER = _gammaController; MARGIN_POOL = _marginPool; GNOSIS_EASY_AUCTION = _gnosisEasyAuction; UNISWAP_ROUTER = _uniswapRouter; UNISWAP_FACTORY = _uniswapFactory; } /** * @notice Initializes the OptionVault contract with storage variables. */ function baseInitialize( address _owner, address _keeper, address _feeRecipient, uint256 _managementFee, uint256 _performanceFee, string memory _tokenName, string memory _tokenSymbol, Vault.VaultParams calldata _vaultParams ) internal initializer { VaultLifecycle.verifyInitializerParams( _owner, _keeper, _feeRecipient, _performanceFee, _managementFee, _tokenName, _tokenSymbol, _vaultParams ); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); keeper = _keeper; feeRecipient = _feeRecipient; performanceFee = _performanceFee; managementFee = _managementFee.mul(Vault.FEE_MULTIPLIER).div( WEEKS_PER_YEAR ); vaultParams = _vaultParams; uint256 assetBalance = IERC20(vaultParams.asset).balanceOf(address(this)); ShareMath.assertUint104(assetBalance); vaultState.lastLockedAmount = uint104(assetBalance); vaultState.round = 1; } /** * @dev Throws if called by any account other than the keeper. */ modifier onlyKeeper() { require(msg.sender == keeper, "!keeper"); _; } /************************************************ * SETTERS ***********************************************/ /** * @notice Sets the new keeper * @param newKeeper is the address of the new keeper */ function setNewKeeper(address newKeeper) external onlyOwner { require(newKeeper != address(0), "!newKeeper"); keeper = newKeeper; } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); require(newFeeRecipient != feeRecipient, "Must be new feeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the management fee for the vault * @param newManagementFee is the management fee (6 decimals). ex: 2 * 10 ** 6 = 2% */ function setManagementFee(uint256 newManagementFee) external onlyOwner { require( newManagementFee < 100 * Vault.FEE_MULTIPLIER, "Invalid management fee" ); // We are dividing annualized management fee by num weeks in a year uint256 tmpManagementFee = newManagementFee.mul(Vault.FEE_MULTIPLIER).div(WEEKS_PER_YEAR); emit ManagementFeeSet(managementFee, newManagementFee); managementFee = tmpManagementFee; } /** * @notice Sets the performance fee for the vault * @param newPerformanceFee is the performance fee (6 decimals). ex: 20 * 10 ** 6 = 20% */ function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner { require( newPerformanceFee < 100 * Vault.FEE_MULTIPLIER, "Invalid performance fee" ); emit PerformanceFeeSet(performanceFee, newPerformanceFee); performanceFee = newPerformanceFee; } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyOwner { require(newCap > 0, "!newCap"); ShareMath.assertUint104(newCap); emit CapSet(vaultParams.cap, newCap); vaultParams.cap = uint104(newCap); } /************************************************ * DEPOSIT & WITHDRAWALS ***********************************************/ /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the asset is not WETH. */ function depositETH() external payable nonReentrant { require(vaultParams.asset == WETH, "!WETH"); require(msg.value > 0, "!value"); _depositFor(msg.value, msg.sender); IWETH(WETH).deposit{value: msg.value}(); } /** * @notice Deposits the `asset` from msg.sender. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { require(amount > 0, "!amount"); _depositFor(amount, msg.sender); // An approve() by the msg.sender is required beforehand IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } /** * @notice Deposits the `asset` from msg.sender added to `creditor`'s deposit. * @notice Used for vault -> vault deposits on the user's behalf * @param amount is the amount of `asset` to deposit * @param creditor is the address that can claim/withdraw deposited amount */ function depositFor(uint256 amount, address creditor) external nonReentrant { require(amount > 0, "!amount"); require(creditor != address(0)); _depositFor(amount, creditor); // An approve() by the msg.sender is required beforehand IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } /** * @notice Mints the vault shares to the creditor * @param amount is the amount of `asset` deposited * @param creditor is the address to receieve the deposit */ function _depositFor(uint256 amount, address creditor) private { uint256 currentRound = vaultState.round; uint256 totalWithDepositedAmount = totalBalance().add(amount); require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap"); require( totalWithDepositedAmount >= vaultParams.minimumSupply, "Insufficient balance" ); emit Deposit(creditor, amount, currentRound); Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor]; // If we have an unprocessed pending deposit from the previous rounds, we have to process it. uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount; // If we have a pending deposit in the current round, we add on to the pending deposit if (currentRound == depositReceipt.round) { uint256 newAmount = uint256(depositReceipt.amount).add(amount); depositAmount = newAmount; } ShareMath.assertUint104(depositAmount); depositReceipts[creditor] = Vault.DepositReceipt({ round: uint16(currentRound), amount: uint104(depositAmount), unredeemedShares: uint128(unredeemedShares) }); uint256 newTotalPending = uint256(vaultState.totalPending).add(amount); ShareMath.assertUint128(newTotalPending); vaultState.totalPending = uint128(newTotalPending); } /** * @notice Initiates a withdrawal that can be processed once the round completes * @param numShares is the number of shares to withdraw */ function initiateWithdraw(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); // We do a max redeem before initiating a withdrawal // But we check if they must first have unredeemed shares if ( depositReceipts[msg.sender].amount > 0 || depositReceipts[msg.sender].unredeemedShares > 0 ) { _redeem(0, true); } // This caches the `round` variable used in shareBalances uint256 currentRound = vaultState.round; Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares; if (withdrawalIsSameRound) { withdrawalShares = existingShares.add(numShares); } else { require(existingShares == 0, "Existing withdraw"); withdrawalShares = numShares; withdrawals[msg.sender].round = uint16(currentRound); } ShareMath.assertUint128(withdrawalShares); withdrawals[msg.sender].shares = uint128(withdrawalShares); uint256 newQueuedWithdrawShares = uint256(vaultState.queuedWithdrawShares).add(numShares); ShareMath.assertUint128(newQueuedWithdrawShares); vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares); _transfer(msg.sender, address(this), numShares); } /** * @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round * @return withdrawAmount the current withdrawal amount */ function _completeWithdraw() internal returns (uint256) { Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; uint256 withdrawalShares = withdrawal.shares; uint256 withdrawalRound = withdrawal.round; // This checks if there is a withdrawal require(withdrawalShares > 0, "Not initiated"); require(withdrawalRound < vaultState.round, "Round not closed"); // We leave the round number as non-zero to save on gas for subsequent writes withdrawals[msg.sender].shares = 0; vaultState.queuedWithdrawShares = uint128( uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares) ); uint256 withdrawAmount = ShareMath.sharesToAsset( withdrawalShares, roundPricePerShare[withdrawalRound], vaultParams.decimals ); emit Withdraw(msg.sender, withdrawAmount, withdrawalShares); _burn(address(this), withdrawalShares); require(withdrawAmount > 0, "!withdrawAmount"); transferAsset(msg.sender, withdrawAmount); return withdrawAmount; } /** * @notice Redeems shares that are owed to the account * @param numShares is the number of shares to redeem */ function redeem(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); _redeem(numShares, false); } /** * @notice Redeems the entire unredeemedShares balance that is owed to the account */ function maxRedeem() external nonReentrant { _redeem(0, true); } /** * @notice Redeems shares that are owed to the account * @param numShares is the number of shares to redeem, could be 0 when isMax=true * @param isMax is flag for when callers do a max redemption */ function _redeem(uint256 numShares, bool isMax) internal { Vault.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; // This handles the null case when depositReceipt.round = 0 // Because we start with round = 1 at `initialize` uint256 currentRound = vaultState.round; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); numShares = isMax ? unredeemedShares : numShares; if (numShares == 0) { return; } require(numShares <= unredeemedShares, "Exceeds available"); // If we have a depositReceipt on the same round, BUT we have some unredeemed shares // we debit from the unredeemedShares, but leave the amount field intact // If the round has past, with no new deposits, we just zero it out for new deposits. if (depositReceipt.round < currentRound) { depositReceipts[msg.sender].amount = 0; } ShareMath.assertUint128(numShares); depositReceipts[msg.sender].unredeemedShares = uint128( unredeemedShares.sub(numShares) ); emit Redeem(msg.sender, numShares, depositReceipt.round); _transfer(address(this), msg.sender, numShares); } /************************************************ * VAULT OPERATIONS ***********************************************/ /* * @notice Helper function that helps to save gas for writing values into the roundPricePerShare map. * Writing `1` into the map makes subsequent writes warm, reducing the gas from 20k to 5k. * Having 1 initialized beforehand will not be an issue as long as we round down share calculations to 0. * @param numRounds is the number of rounds to initialize in the map */ function initRounds(uint256 numRounds) external nonReentrant { require(numRounds > 0, "!numRounds"); uint256 _round = vaultState.round; for (uint256 i = 0; i < numRounds; i++) { uint256 index = _round + i; require(roundPricePerShare[index] == 0, "Initialized"); // AVOID OVERWRITING ACTUAL VALUES roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT; } } /* * @notice Helper function that performs most administrative tasks * such as setting next option, minting new shares, getting vault fees, etc. * @param lastQueuedWithdrawAmount is old queued withdraw amount * @return newOption is the new option address * @return lockedBalance is the new balance used to calculate next option purchase size or collateral size * @return queuedWithdrawAmount is the new queued withdraw amount for this round */ function _rollToNextOption(uint256 lastQueuedWithdrawAmount) internal returns ( address newOption, uint256 lockedBalance, uint256 queuedWithdrawAmount ) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); address recipient = feeRecipient; uint256 mintShares; uint256 performanceFeeInAsset; uint256 totalVaultFee; { uint256 newPricePerShare; ( lockedBalance, queuedWithdrawAmount, newPricePerShare, mintShares, performanceFeeInAsset, totalVaultFee ) = VaultLifecycle.rollover( vaultState, VaultLifecycle.RolloverParams( vaultParams.decimals, IERC20(vaultParams.asset).balanceOf(address(this)), totalSupply(), lastQueuedWithdrawAmount, performanceFee, managementFee ) ); optionState.currentOption = newOption; optionState.nextOption = address(0); // Finalize the pricePerShare at the end of the round uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; emit CollectVaultFees( performanceFeeInAsset, totalVaultFee, currentRound, recipient ); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); } _mint(address(this), mintShares); if (totalVaultFee > 0) { transferAsset(payable(recipient), totalVaultFee); } return (newOption, lockedBalance, queuedWithdrawAmount); } /** * @notice Helper function to make either an ETH transfer or ERC20 transfer * @param recipient is the receiving address * @param amount is the transfer amount */ function transferAsset(address recipient, uint256 amount) internal { address asset = vaultParams.asset; if (asset == WETH) { IWETH(WETH).withdraw(amount); (bool success, ) = recipient.call{value: amount}(""); require(success, "Transfer failed"); return; } IERC20(asset).safeTransfer(recipient, amount); } /************************************************ * GETTERS ***********************************************/ /** * @notice Returns the asset balance held on the vault for the account * @param account is the address to lookup balance for * @return the amount of `asset` custodied by the vault for the user */ function accountVaultBalance(address account) external view returns (uint256) { uint256 _decimals = vaultParams.decimals; uint256 assetPerShare = ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, _decimals ); return ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals); } /** * @notice Getter for returning the account's share balance including unredeemed shares * @param account is the account to lookup share balance for * @return the share balance */ function shares(address account) public view returns (uint256) { (uint256 heldByAccount, uint256 heldByVault) = shareBalances(account); return heldByAccount.add(heldByVault); } /** * @notice Getter for returning the account's share balance split between account and vault holdings * @param account is the account to lookup share balance for * @return heldByAccount is the shares held by account * @return heldByVault is the shares held on the vault (unredeemedShares) */ function shareBalances(address account) public view returns (uint256 heldByAccount, uint256 heldByVault) { Vault.DepositReceipt memory depositReceipt = depositReceipts[account]; if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) { return (balanceOf(account), 0); } uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( vaultState.round, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); return (balanceOf(account), unredeemedShares); } /** * @notice The price of a unit of share denominated in the `asset` */ function pricePerShare() external view returns (uint256) { return ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, vaultParams.decimals ); } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return uint256(vaultState.lockedAmount).add( IERC20(vaultParams.asset).balanceOf(address(this)) ); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return vaultParams.decimals; } function cap() external view returns (uint256) { return vaultParams.cap; } function nextOptionReadyAt() external view returns (uint256) { return optionState.nextOptionReadyAt; } function currentOption() external view returns (address) { return optionState.currentOption; } function nextOption() external view returns (address) { return optionState.nextOption; } function totalPending() external view returns (uint256) { return vaultState.totalPending; } /************************************************ * HELPERS ***********************************************/ /** * @notice Helper to check whether swap path goes from stables (USDC) to vault's underlying asset * @param swapPath is the swap path e.g. encodePacked(tokenIn, poolFee, tokenOut) * @return boolean whether the path is valid */ function _checkPath(bytes calldata swapPath) internal view returns (bool) { return VaultLifecycle.checkPath( swapPath, USDC, vaultParams.asset, UNISWAP_FACTORY ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; library DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; //rounds to zero if x*y < WAD / 2 function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library AuctionType { struct AuctionData { IERC20 auctioningToken; IERC20 biddingToken; uint256 orderCancellationEndDate; uint256 auctionEndDate; bytes32 initialAuctionOrder; uint256 minimumBiddingAmountPerOrder; uint256 interimSumBidAmount; bytes32 interimOrder; bytes32 clearingPriceOrder; uint96 volumeClearingPriceOrder; bool minFundingThresholdNotReached; bool isAtomicClosureAllowed; uint256 feeNumerator; uint256 minFundingThreshold; } } interface IGnosisAuction { function initiateAuction( address _auctioningToken, address _biddingToken, uint256 orderCancellationEndDate, uint256 auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 minimumBiddingAmountPerOrder, uint256 minFundingThreshold, bool isAtomicClosureAllowed, address accessManagerContract, bytes memory accessManagerContractData ) external returns (uint256); function auctionCounter() external view returns (uint256); function auctionData(uint256 auctionId) external view returns (AuctionType.AuctionData memory); function auctionAccessManager(uint256 auctionId) external view returns (address); function auctionAccessData(uint256 auctionId) external view returns (bytes memory); function FEE_DENOMINATOR() external view returns (uint256); function feeNumerator() external view returns (uint256); function settleAuction(uint256 auctionId) external returns (bytes32); function placeSellOrders( uint256 auctionId, uint96[] memory _minBuyAmounts, uint96[] memory _sellAmounts, bytes32[] memory _prevSellOrders, bytes calldata allowListCallData ) external returns (uint64); function claimFromParticipantOrder( uint256 auctionId, bytes32[] memory orders ) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; library GammaTypes { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral // in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } interface IOtoken { function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); } interface IOtokenFactory { function getOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); function createOtoken( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external returns (address); function getTargetOtokenAddress( address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external view returns (address); event OtokenCreated( address tokenAddress, address creator, address indexed underlying, address indexed strike, address indexed collateral, uint256 strikePrice, uint256 expiry, bool isPut ); } interface IController { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets // but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function operate(ActionArgs[] calldata _actions) external; function getAccountVaultCounter(address owner) external view returns (uint256); function oracle() external view returns (address); function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory); function getProceed(address _owner, uint256 _vaultId) external view returns (uint256); function isSettlementAllowed( address _underlying, address _strike, address _collateral, uint256 _expiry ) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IStrikeSelection { function getStrikePrice(uint256 expiryTimestamp, bool isPut) external view returns (uint256, uint256); function delta() external view returns (uint256); } interface IOptionsPremiumPricer { function getPremium( uint256 strikePrice, uint256 timeToExpiry, bool isPut ) external view returns (uint256); function getOptionDelta( uint256 spotPrice, uint256 strikePrice, uint256 volatility, uint256 expiryTimestamp ) external view returns (uint256 delta); function getUnderlyingPrice() external view returns (uint256); function priceOracle() external view returns (address); function volatilityOracle() external view returns (address); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {Vault} from "../libraries/Vault.sol"; interface IRibbonThetaVault { function currentOption() external view returns (address); function nextOption() external view returns (address); function vaultParams() external view returns (Vault.VaultParams memory); function vaultState() external view returns (Vault.VaultState memory); function optionState() external view returns (Vault.OptionState memory); function optionAuctionID() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Detailed is IERC20 { function decimals() external view returns (uint8); function symbol() external view returns (string calldata); function name() external view returns (string calldata); } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * This library supports ERC20s that have quirks in their behavior. * One such ERC20 is USDT, which requires allowance to be 0 before calling approve. * We plan to update this library with ERC20s that display such idiosyncratic behavior. */ library SupportsNonCompliantERC20 { address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; function safeApproveNonCompliant( IERC20 token, address spender, uint256 amount ) internal { if (address(token) == USDT) { SafeERC20.safeApprove(token, spender, 0); } SafeERC20.safeApprove(token, spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ISwapRouter} from "../interfaces/ISwapRouter.sol"; import {IUniswapV3Factory} from "../interfaces/IUniswapV3Factory.sol"; import "./Path.sol"; library UniswapRouter { using Path for bytes; using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Check if the path set for swap is valid * @param swapPath is the swap path e.g. encodePacked(tokenIn, poolFee, tokenOut) * @param validTokenIn is the contract address of the correct tokenIn * @param validTokenOut is the contract address of the correct tokenOut * @param uniswapFactory is the contract address of UniswapV3 factory * @return isValidPath is whether the path is valid */ function checkPath( bytes memory swapPath, address validTokenIn, address validTokenOut, address uniswapFactory ) internal view returns (bool isValidPath) { // Function checks if the tokenIn and tokenOut in the swapPath // matches the validTokenIn and validTokenOut specified. address tokenIn; address tokenOut; address tempTokenIn; uint24 fee; IUniswapV3Factory factory = IUniswapV3Factory(uniswapFactory); // Return early if swapPath is below the bare minimum (43) require(swapPath.length >= 43, "Path too short"); // Return early if swapPath is above the max (66) // At worst we have 2 hops e.g. USDC > WETH > asset require(swapPath.length <= 66, "Path too long"); // Decode the first pool in path (tokenIn, tokenOut, fee) = swapPath.decodeFirstPool(); // Check to factory if pool exists require( factory.getPool(tokenIn, tokenOut, fee) != address(0), "Pool does not exist" ); // Check next pool if multiple pools while (swapPath.hasMultiplePools()) { // Remove the first pool from path swapPath = swapPath.skipToken(); // Check the next pool and update tokenOut (tempTokenIn, tokenOut, fee) = swapPath.decodeFirstPool(); require( factory.getPool(tokenIn, tokenOut, fee) != address(0), "Pool does not exist" ); } return tokenIn == validTokenIn && tokenOut == validTokenOut; } /** * @notice Swaps assets by calling UniswapV3 router * @param recipient is the address of recipient of the tokenOut * @param tokenIn is the address of the token given to the router * @param amountIn is the amount of tokenIn given to the router * @param minAmountOut is the minimum acceptable amount of tokenOut received from swap * @param router is the contract address of UniswapV3 router * @param swapPath is the swap path e.g. encodePacked(tokenIn, poolFee, tokenOut) * @return amountOut is the amount of tokenOut received from the swap */ function swap( address recipient, address tokenIn, uint256 amountIn, uint256 minAmountOut, address router, bytes calldata swapPath ) internal returns (uint256 amountOut) { // Approve router to spend tokenIn IERC20(tokenIn).safeApprove(router, amountIn); // Swap assets using UniswapV3 router ISwapRouter.ExactInputParams memory swapParams = ISwapRouter.ExactInputParams({ recipient: recipient, path: swapPath, deadline: block.timestamp.add(10 minutes), amountIn: amountIn, amountOutMinimum: minAmountOut }); amountOut = ISwapRouter(router).exactInput(swapParams); return amountOut; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.8.4; pragma abicoder v2; /// Source: https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/callback/IUniswapV3SwapCallback.sol /// @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; } /// Source: https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISwapRouter.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 // Source: https://github.com/Uniswap/v3-core/blob/main/contracts/interfaces/IUniswapV3Factory.sol pragma solidity =0.8.4; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later // Source: https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/Path.sol pragma solidity =0.8.4; import "./BytesLib.sol"; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Returns the number of pools in the path /// @param path The encoded swap path /// @return The number of pools in the path function numPools(bytes memory path) internal pure returns (uint256) { // Ignore the first token address. From then on every fee and token offset indicates a pool. return ((path.length - ADDR_SIZE) / NEXT_OFFSET); } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT // Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity =0.8.4; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add( add( add(_bytes, lengthmod), mul(0x20, iszero(lengthmod)) ), _start ) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div( mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000 ) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_bytes.length >= _start + 3, "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // 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 { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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); }
no access to critical vault changes Gap is left to avoid storage collisions. Though RibbonVault is not upgradeable, we add this as a safety measure. *IMPORTANT* NO NEW STORAGE VARIABLES SHOULD BE ADDED HERE This is to prevent storage collisions. All storage variables should be appended to RibbonThetaVaultStorage or RibbonDeltaVaultStorage instead. Read this documentation to learn more: https:docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts Number of weeks per year = 52.142857 weeks * FEE_MULTIPLIER = 52142857 Dividing by weeks per year requires doing num.mul(FEE_MULTIPLIER).div(WEEKS_PER_YEAR) GAMMA_CONTROLLER is the top-level contract in Gamma protocol which allows users to perform multiple actions on their vaults and positions https:github.com/opynfinance/GammaProtocol/blob/master/contracts/core/Controller.sol MARGIN_POOL is Gamma protocol's collateral pool. Needed to approve collateral.safeTransferFrom for minting otokens. https:github.com/opynfinance/GammaProtocol/blob/master/contracts/core/MarginPool.sol GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids https:github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol UNISWAP_ROUTER is the contract address of UniswapV3 Router which handles swaps https:github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISwapRouter.sol UNISWAP_FACTORY is the contract address of UniswapV3 Factory which stores pool information https:github.com/Uniswap/v3-core/blob/main/contracts/interfaces/IUniswapV3Factory.sol
{ using SafeERC20 for IERC20; using SafeMath for uint256; using ShareMath for Vault.DepositReceipt; mapping(address => Vault.DepositReceipt) public depositReceipts; mapping(uint256 => uint256) public roundPricePerShare; mapping(address => Vault.Withdrawal) public withdrawals; Vault.VaultParams public vaultParams; Vault.VaultState public vaultState; Vault.OptionState public optionState; address public feeRecipient; address public keeper; uint256 public performanceFee; uint256 public managementFee; uint256[30] private ____gap; address public immutable WETH; address public immutable USDC; uint256 public constant DELAY = 15 minutes; uint256 public constant PERIOD = 7 days; uint256 private constant WEEKS_PER_YEAR = 52142857; address public immutable GAMMA_CONTROLLER; address public immutable MARGIN_POOL; address public immutable GNOSIS_EASY_AUCTION; address public immutable UNISWAP_ROUTER; address public immutable UNISWAP_FACTORY; event Deposit(address indexed account, uint256 amount, uint256 round); event InitiateWithdraw( address indexed account, uint256 shares, uint256 round ); event Redeem(address indexed account, uint256 share, uint256 round); event ManagementFeeSet(uint256 managementFee, uint256 newManagementFee); event PerformanceFeeSet(uint256 performanceFee, uint256 newPerformanceFee); event CapSet(uint256 oldCap, uint256 newCap); event Withdraw(address indexed account, uint256 amount, uint256 shares); event CollectVaultFees( uint256 performanceFee, uint256 vaultFee, uint256 round, address indexed feeRecipient ); constructor( address _weth, address _usdc, address _gammaController, address _marginPool, address _gnosisEasyAuction, address _uniswapRouter, address _uniswapFactory import {Vault} from "../../../libraries/Vault.sol"; import {VaultLifecycle} from "../../../libraries/VaultLifecycle.sol"; import {ShareMath} from "../../../libraries/ShareMath.sol"; import {IWETH} from "../../../interfaces/IWETH.sol"; ) { require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_gnosisEasyAuction != address(0), "!_gnosisEasyAuction"); require(_gammaController != address(0), "!_gammaController"); require(_marginPool != address(0), "!_marginPool"); require(_uniswapRouter != address(0), "!_uniswapRouter"); require(_uniswapFactory != address(0), "!_uniswapFactory"); WETH = _weth; USDC = _usdc; GAMMA_CONTROLLER = _gammaController; MARGIN_POOL = _marginPool; GNOSIS_EASY_AUCTION = _gnosisEasyAuction; UNISWAP_ROUTER = _uniswapRouter; UNISWAP_FACTORY = _uniswapFactory; } function baseInitialize( address _owner, address _keeper, address _feeRecipient, uint256 _managementFee, uint256 _performanceFee, string memory _tokenName, string memory _tokenSymbol, Vault.VaultParams calldata _vaultParams ) internal initializer { VaultLifecycle.verifyInitializerParams( _owner, _keeper, _feeRecipient, _performanceFee, _managementFee, _tokenName, _tokenSymbol, _vaultParams ); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); keeper = _keeper; feeRecipient = _feeRecipient; performanceFee = _performanceFee; managementFee = _managementFee.mul(Vault.FEE_MULTIPLIER).div( WEEKS_PER_YEAR ); vaultParams = _vaultParams; uint256 assetBalance = IERC20(vaultParams.asset).balanceOf(address(this)); ShareMath.assertUint104(assetBalance); vaultState.lastLockedAmount = uint104(assetBalance); vaultState.round = 1; } modifier onlyKeeper() { require(msg.sender == keeper, "!keeper"); _; } function setNewKeeper(address newKeeper) external onlyOwner { require(newKeeper != address(0), "!newKeeper"); keeper = newKeeper; } function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); require(newFeeRecipient != feeRecipient, "Must be new feeRecipient"); feeRecipient = newFeeRecipient; } function setManagementFee(uint256 newManagementFee) external onlyOwner { require( newManagementFee < 100 * Vault.FEE_MULTIPLIER, "Invalid management fee" ); uint256 tmpManagementFee = newManagementFee.mul(Vault.FEE_MULTIPLIER).div(WEEKS_PER_YEAR); emit ManagementFeeSet(managementFee, newManagementFee); managementFee = tmpManagementFee; } function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner { require( newPerformanceFee < 100 * Vault.FEE_MULTIPLIER, "Invalid performance fee" ); emit PerformanceFeeSet(performanceFee, newPerformanceFee); performanceFee = newPerformanceFee; } function setCap(uint256 newCap) external onlyOwner { require(newCap > 0, "!newCap"); ShareMath.assertUint104(newCap); emit CapSet(vaultParams.cap, newCap); vaultParams.cap = uint104(newCap); } function depositETH() external payable nonReentrant { require(vaultParams.asset == WETH, "!WETH"); require(msg.value > 0, "!value"); _depositFor(msg.value, msg.sender); } IWETH(WETH).deposit{value: msg.value}(); function deposit(uint256 amount) external nonReentrant { require(amount > 0, "!amount"); _depositFor(amount, msg.sender); IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } function depositFor(uint256 amount, address creditor) external nonReentrant { require(amount > 0, "!amount"); require(creditor != address(0)); _depositFor(amount, creditor); IERC20(vaultParams.asset).safeTransferFrom( msg.sender, address(this), amount ); } function _depositFor(uint256 amount, address creditor) private { uint256 currentRound = vaultState.round; uint256 totalWithDepositedAmount = totalBalance().add(amount); require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap"); require( totalWithDepositedAmount >= vaultParams.minimumSupply, "Insufficient balance" ); emit Deposit(creditor, amount, currentRound); Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor]; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount; if (currentRound == depositReceipt.round) { uint256 newAmount = uint256(depositReceipt.amount).add(amount); depositAmount = newAmount; } ShareMath.assertUint104(depositAmount); depositReceipts[creditor] = Vault.DepositReceipt({ round: uint16(currentRound), amount: uint104(depositAmount), unredeemedShares: uint128(unredeemedShares) }); uint256 newTotalPending = uint256(vaultState.totalPending).add(amount); ShareMath.assertUint128(newTotalPending); vaultState.totalPending = uint128(newTotalPending); } function _depositFor(uint256 amount, address creditor) private { uint256 currentRound = vaultState.round; uint256 totalWithDepositedAmount = totalBalance().add(amount); require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap"); require( totalWithDepositedAmount >= vaultParams.minimumSupply, "Insufficient balance" ); emit Deposit(creditor, amount, currentRound); Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor]; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount; if (currentRound == depositReceipt.round) { uint256 newAmount = uint256(depositReceipt.amount).add(amount); depositAmount = newAmount; } ShareMath.assertUint104(depositAmount); depositReceipts[creditor] = Vault.DepositReceipt({ round: uint16(currentRound), amount: uint104(depositAmount), unredeemedShares: uint128(unredeemedShares) }); uint256 newTotalPending = uint256(vaultState.totalPending).add(amount); ShareMath.assertUint128(newTotalPending); vaultState.totalPending = uint128(newTotalPending); } function _depositFor(uint256 amount, address creditor) private { uint256 currentRound = vaultState.round; uint256 totalWithDepositedAmount = totalBalance().add(amount); require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap"); require( totalWithDepositedAmount >= vaultParams.minimumSupply, "Insufficient balance" ); emit Deposit(creditor, amount, currentRound); Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor]; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); uint256 depositAmount = amount; if (currentRound == depositReceipt.round) { uint256 newAmount = uint256(depositReceipt.amount).add(amount); depositAmount = newAmount; } ShareMath.assertUint104(depositAmount); depositReceipts[creditor] = Vault.DepositReceipt({ round: uint16(currentRound), amount: uint104(depositAmount), unredeemedShares: uint128(unredeemedShares) }); uint256 newTotalPending = uint256(vaultState.totalPending).add(amount); ShareMath.assertUint128(newTotalPending); vaultState.totalPending = uint128(newTotalPending); } function initiateWithdraw(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); if ( depositReceipts[msg.sender].amount > 0 || depositReceipts[msg.sender].unredeemedShares > 0 ) { _redeem(0, true); } Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares; if (withdrawalIsSameRound) { withdrawalShares = existingShares.add(numShares); require(existingShares == 0, "Existing withdraw"); withdrawalShares = numShares; withdrawals[msg.sender].round = uint16(currentRound); } ShareMath.assertUint128(withdrawalShares); withdrawals[msg.sender].shares = uint128(withdrawalShares); uint256 newQueuedWithdrawShares = uint256(vaultState.queuedWithdrawShares).add(numShares); ShareMath.assertUint128(newQueuedWithdrawShares); vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares); _transfer(msg.sender, address(this), numShares); } function initiateWithdraw(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); if ( depositReceipts[msg.sender].amount > 0 || depositReceipts[msg.sender].unredeemedShares > 0 ) { _redeem(0, true); } Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares; if (withdrawalIsSameRound) { withdrawalShares = existingShares.add(numShares); require(existingShares == 0, "Existing withdraw"); withdrawalShares = numShares; withdrawals[msg.sender].round = uint16(currentRound); } ShareMath.assertUint128(withdrawalShares); withdrawals[msg.sender].shares = uint128(withdrawalShares); uint256 newQueuedWithdrawShares = uint256(vaultState.queuedWithdrawShares).add(numShares); ShareMath.assertUint128(newQueuedWithdrawShares); vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares); _transfer(msg.sender, address(this), numShares); } uint256 currentRound = vaultState.round; function initiateWithdraw(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); if ( depositReceipts[msg.sender].amount > 0 || depositReceipts[msg.sender].unredeemedShares > 0 ) { _redeem(0, true); } Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares; if (withdrawalIsSameRound) { withdrawalShares = existingShares.add(numShares); require(existingShares == 0, "Existing withdraw"); withdrawalShares = numShares; withdrawals[msg.sender].round = uint16(currentRound); } ShareMath.assertUint128(withdrawalShares); withdrawals[msg.sender].shares = uint128(withdrawalShares); uint256 newQueuedWithdrawShares = uint256(vaultState.queuedWithdrawShares).add(numShares); ShareMath.assertUint128(newQueuedWithdrawShares); vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares); _transfer(msg.sender, address(this), numShares); } } else { function _completeWithdraw() internal returns (uint256) { Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; uint256 withdrawalShares = withdrawal.shares; uint256 withdrawalRound = withdrawal.round; require(withdrawalShares > 0, "Not initiated"); require(withdrawalRound < vaultState.round, "Round not closed"); withdrawals[msg.sender].shares = 0; vaultState.queuedWithdrawShares = uint128( uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares) ); uint256 withdrawAmount = ShareMath.sharesToAsset( withdrawalShares, roundPricePerShare[withdrawalRound], vaultParams.decimals ); emit Withdraw(msg.sender, withdrawAmount, withdrawalShares); _burn(address(this), withdrawalShares); require(withdrawAmount > 0, "!withdrawAmount"); transferAsset(msg.sender, withdrawAmount); return withdrawAmount; } function redeem(uint256 numShares) external nonReentrant { require(numShares > 0, "!numShares"); _redeem(numShares, false); } function maxRedeem() external nonReentrant { _redeem(0, true); } function _redeem(uint256 numShares, bool isMax) internal { Vault.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; uint256 currentRound = vaultState.round; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); numShares = isMax ? unredeemedShares : numShares; if (numShares == 0) { return; } require(numShares <= unredeemedShares, "Exceeds available"); if (depositReceipt.round < currentRound) { depositReceipts[msg.sender].amount = 0; } ShareMath.assertUint128(numShares); depositReceipts[msg.sender].unredeemedShares = uint128( unredeemedShares.sub(numShares) ); emit Redeem(msg.sender, numShares, depositReceipt.round); _transfer(address(this), msg.sender, numShares); } function _redeem(uint256 numShares, bool isMax) internal { Vault.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; uint256 currentRound = vaultState.round; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); numShares = isMax ? unredeemedShares : numShares; if (numShares == 0) { return; } require(numShares <= unredeemedShares, "Exceeds available"); if (depositReceipt.round < currentRound) { depositReceipts[msg.sender].amount = 0; } ShareMath.assertUint128(numShares); depositReceipts[msg.sender].unredeemedShares = uint128( unredeemedShares.sub(numShares) ); emit Redeem(msg.sender, numShares, depositReceipt.round); _transfer(address(this), msg.sender, numShares); } function _redeem(uint256 numShares, bool isMax) internal { Vault.DepositReceipt memory depositReceipt = depositReceipts[msg.sender]; uint256 currentRound = vaultState.round; uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( currentRound, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); numShares = isMax ? unredeemedShares : numShares; if (numShares == 0) { return; } require(numShares <= unredeemedShares, "Exceeds available"); if (depositReceipt.round < currentRound) { depositReceipts[msg.sender].amount = 0; } ShareMath.assertUint128(numShares); depositReceipts[msg.sender].unredeemedShares = uint128( unredeemedShares.sub(numShares) ); emit Redeem(msg.sender, numShares, depositReceipt.round); _transfer(address(this), msg.sender, numShares); } function initRounds(uint256 numRounds) external nonReentrant { require(numRounds > 0, "!numRounds"); uint256 _round = vaultState.round; for (uint256 i = 0; i < numRounds; i++) { uint256 index = _round + i; roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT; } } function initRounds(uint256 numRounds) external nonReentrant { require(numRounds > 0, "!numRounds"); uint256 _round = vaultState.round; for (uint256 i = 0; i < numRounds; i++) { uint256 index = _round + i; roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT; } } function _rollToNextOption(uint256 lastQueuedWithdrawAmount) internal returns ( address newOption, uint256 lockedBalance, uint256 queuedWithdrawAmount ) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); address recipient = feeRecipient; uint256 mintShares; uint256 performanceFeeInAsset; uint256 totalVaultFee; { uint256 newPricePerShare; ( lockedBalance, queuedWithdrawAmount, newPricePerShare, mintShares, performanceFeeInAsset, totalVaultFee ) = VaultLifecycle.rollover( vaultState, VaultLifecycle.RolloverParams( vaultParams.decimals, IERC20(vaultParams.asset).balanceOf(address(this)), totalSupply(), lastQueuedWithdrawAmount, performanceFee, managementFee ) ); optionState.currentOption = newOption; optionState.nextOption = address(0); uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; emit CollectVaultFees( performanceFeeInAsset, totalVaultFee, currentRound, recipient ); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); } _mint(address(this), mintShares); if (totalVaultFee > 0) { transferAsset(payable(recipient), totalVaultFee); } return (newOption, lockedBalance, queuedWithdrawAmount); } function _rollToNextOption(uint256 lastQueuedWithdrawAmount) internal returns ( address newOption, uint256 lockedBalance, uint256 queuedWithdrawAmount ) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); address recipient = feeRecipient; uint256 mintShares; uint256 performanceFeeInAsset; uint256 totalVaultFee; { uint256 newPricePerShare; ( lockedBalance, queuedWithdrawAmount, newPricePerShare, mintShares, performanceFeeInAsset, totalVaultFee ) = VaultLifecycle.rollover( vaultState, VaultLifecycle.RolloverParams( vaultParams.decimals, IERC20(vaultParams.asset).balanceOf(address(this)), totalSupply(), lastQueuedWithdrawAmount, performanceFee, managementFee ) ); optionState.currentOption = newOption; optionState.nextOption = address(0); uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; emit CollectVaultFees( performanceFeeInAsset, totalVaultFee, currentRound, recipient ); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); } _mint(address(this), mintShares); if (totalVaultFee > 0) { transferAsset(payable(recipient), totalVaultFee); } return (newOption, lockedBalance, queuedWithdrawAmount); } function _rollToNextOption(uint256 lastQueuedWithdrawAmount) internal returns ( address newOption, uint256 lockedBalance, uint256 queuedWithdrawAmount ) { require(block.timestamp >= optionState.nextOptionReadyAt, "!ready"); newOption = optionState.nextOption; require(newOption != address(0), "!nextOption"); address recipient = feeRecipient; uint256 mintShares; uint256 performanceFeeInAsset; uint256 totalVaultFee; { uint256 newPricePerShare; ( lockedBalance, queuedWithdrawAmount, newPricePerShare, mintShares, performanceFeeInAsset, totalVaultFee ) = VaultLifecycle.rollover( vaultState, VaultLifecycle.RolloverParams( vaultParams.decimals, IERC20(vaultParams.asset).balanceOf(address(this)), totalSupply(), lastQueuedWithdrawAmount, performanceFee, managementFee ) ); optionState.currentOption = newOption; optionState.nextOption = address(0); uint256 currentRound = vaultState.round; roundPricePerShare[currentRound] = newPricePerShare; emit CollectVaultFees( performanceFeeInAsset, totalVaultFee, currentRound, recipient ); vaultState.totalPending = 0; vaultState.round = uint16(currentRound + 1); } _mint(address(this), mintShares); if (totalVaultFee > 0) { transferAsset(payable(recipient), totalVaultFee); } return (newOption, lockedBalance, queuedWithdrawAmount); } function transferAsset(address recipient, uint256 amount) internal { address asset = vaultParams.asset; if (asset == WETH) { IWETH(WETH).withdraw(amount); require(success, "Transfer failed"); return; } IERC20(asset).safeTransfer(recipient, amount); } function transferAsset(address recipient, uint256 amount) internal { address asset = vaultParams.asset; if (asset == WETH) { IWETH(WETH).withdraw(amount); require(success, "Transfer failed"); return; } IERC20(asset).safeTransfer(recipient, amount); } (bool success, ) = recipient.call{value: amount}(""); function accountVaultBalance(address account) external view returns (uint256) { uint256 _decimals = vaultParams.decimals; uint256 assetPerShare = ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, _decimals ); return ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals); } function shares(address account) public view returns (uint256) { (uint256 heldByAccount, uint256 heldByVault) = shareBalances(account); return heldByAccount.add(heldByVault); } function shareBalances(address account) public view returns (uint256 heldByAccount, uint256 heldByVault) { Vault.DepositReceipt memory depositReceipt = depositReceipts[account]; if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) { return (balanceOf(account), 0); } uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( vaultState.round, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); return (balanceOf(account), unredeemedShares); } function shareBalances(address account) public view returns (uint256 heldByAccount, uint256 heldByVault) { Vault.DepositReceipt memory depositReceipt = depositReceipts[account]; if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) { return (balanceOf(account), 0); } uint256 unredeemedShares = depositReceipt.getSharesFromReceipt( vaultState.round, roundPricePerShare[depositReceipt.round], vaultParams.decimals ); return (balanceOf(account), unredeemedShares); } function pricePerShare() external view returns (uint256) { return ShareMath.pricePerShare( totalSupply(), totalBalance(), vaultState.totalPending, vaultParams.decimals ); } function totalBalance() public view returns (uint256) { return uint256(vaultState.lockedAmount).add( IERC20(vaultParams.asset).balanceOf(address(this)) ); } function decimals() public view override returns (uint8) { return vaultParams.decimals; } function cap() external view returns (uint256) { return vaultParams.cap; } function nextOptionReadyAt() external view returns (uint256) { return optionState.nextOptionReadyAt; } function currentOption() external view returns (address) { return optionState.currentOption; } function nextOption() external view returns (address) { return optionState.nextOption; } function totalPending() external view returns (uint256) { return vaultState.totalPending; } function _checkPath(bytes calldata swapPath) internal view returns (bool) { return VaultLifecycle.checkPath( swapPath, USDC, vaultParams.asset, UNISWAP_FACTORY ); } }
13,898,161
[ 1, 2135, 2006, 358, 11239, 9229, 3478, 611, 438, 353, 2002, 358, 4543, 2502, 27953, 18, 935, 4966, 534, 495, 18688, 12003, 353, 486, 8400, 429, 16, 732, 527, 333, 487, 279, 24179, 6649, 18, 21840, 6856, 3741, 12887, 2347, 15553, 22965, 55, 6122, 31090, 9722, 11738, 7660, 670, 29340, 1220, 353, 358, 5309, 2502, 27953, 18, 4826, 2502, 3152, 1410, 506, 12317, 358, 534, 495, 18688, 31189, 12003, 3245, 578, 534, 495, 18688, 9242, 12003, 3245, 3560, 18, 2720, 333, 7323, 358, 16094, 1898, 30, 2333, 30, 8532, 18, 3190, 94, 881, 84, 292, 267, 18, 832, 19, 416, 13088, 17, 8057, 19, 21, 18, 92, 19, 14345, 17, 15097, 429, 17042, 310, 17, 93, 477, 17, 16351, 87, 3588, 434, 17314, 1534, 3286, 273, 18106, 18, 3461, 6030, 10321, 17314, 225, 478, 9383, 67, 24683, 2053, 654, 273, 18106, 3461, 6030, 10321, 21411, 10415, 635, 17314, 1534, 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, 95, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 25805, 10477, 364, 17329, 18, 758, 1724, 15636, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 17329, 18, 758, 1724, 15636, 13, 1071, 443, 1724, 4779, 27827, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 3643, 5147, 2173, 9535, 31, 203, 203, 565, 2874, 12, 2867, 516, 17329, 18, 1190, 9446, 287, 13, 1071, 598, 9446, 1031, 31, 203, 203, 565, 17329, 18, 12003, 1370, 1071, 9229, 1370, 31, 203, 203, 565, 17329, 18, 12003, 1119, 1071, 9229, 1119, 31, 203, 203, 565, 17329, 18, 1895, 1119, 1071, 1456, 1119, 31, 203, 203, 565, 1758, 1071, 14036, 18241, 31, 203, 203, 565, 1758, 1071, 417, 9868, 31, 203, 203, 565, 2254, 5034, 1071, 9239, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 11803, 14667, 31, 203, 203, 565, 2254, 5034, 63, 5082, 65, 3238, 19608, 67, 14048, 31, 203, 203, 203, 203, 565, 1758, 1071, 11732, 678, 1584, 44, 31, 203, 203, 565, 1758, 1071, 11732, 11836, 5528, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 2030, 7868, 273, 4711, 6824, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 10950, 21054, 273, 2371, 4681, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 26664, 55, 67, 3194, 67, 15137, 273, 18106, 3461, 6030, 10321, 31, 203, 203, 565, 1758, 1071, 11732, 611, 2192, 5535, 67, 6067, 25353, 31, 203, 203, 565, 1758, 1071, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-04-24 */ // File: contracts/lib/Context.sol // From package @openzeppelin/[email protected] pragma solidity 0.5.8; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/lib/Ownable.sol // From package @openzeppelin/[email protected] pragma solidity 0.5.8; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/lib/SafeMath.sol // From package @openzeppelin/[email protected] pragma solidity 0.5.8; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/lib/lib.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* Everest is using the dai contracts to mock the real dai that will be used. This contract lives here: https://github.com/makerdao/dss/blob/master/src/lib.sol Also we changed the pragma from 0.5.12 to ^0.5.8 */ pragma solidity 0.5.8; contract LibNote { event LogNote( bytes4 indexed sig, address indexed usr, bytes32 indexed arg1, bytes32 indexed arg2, bytes data ) anonymous; modifier note { _; /* solium-disable-next-line security/no-inline-assembly*/ assembly { // log an 'anonymous' event with a constant 6 words of calldata // and four indexed topics: selector, caller, arg1 and arg2 let mark := msize // end of memory ensures zero mstore(0x40, add(mark, 288)) // update free memory pointer mstore(mark, 0x20) // bytes type data offset mstore(add(mark, 0x20), 224) // bytes size (padded) calldatacopy(add(mark, 0x40), 0, 224) // bytes payload log4(mark, 288, // calldata shl(224, shr(224, calldataload(0))), // msg.sig caller, // msg.sender calldataload(4), // arg1 calldataload(36) // arg2 ) } } } // File: contracts/lib/dai.sol // Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* Everest is using the dai contracts to mock the real dai that will be used. This contract lives here: https://github.com/makerdao/dss/blob/master/src/dai.sol Also we changed the pragma from 0.5.12 to ^0.5.8 */ pragma solidity 0.5.8; contract Dai is LibNote { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external note auth { wards[guy] = 1; } function deny(address guy) external note auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "Dai/not-authorized"); _; } // --- ERC20 Data --- string public constant name = "Dai Stablecoin"; string public constant symbol = "DAI"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); // --- Math --- function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; constructor(uint256 chainId_) public { wards[msg.sender] = 1; DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId_, address(this) )); } // --- Token --- function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad, "Dai/insufficient-balance"); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad, "Dai/insufficient-allowance"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function mint(address usr, uint wad) external auth { balanceOf[usr] = add(balanceOf[usr], wad); totalSupply = add(totalSupply, wad); emit Transfer(address(0), usr, wad); } function burn(address usr, uint wad) external { require(balanceOf[usr] >= wad, "Dai/insufficient-balance"); if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) { require(allowance[usr][msg.sender] >= wad, "Dai/insufficient-allowance"); allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad); } balanceOf[usr] = sub(balanceOf[usr], wad); totalSupply = sub(totalSupply, wad); emit Transfer(usr, address(0), wad); } function approve(address usr, uint wad) external returns (bool) { allowance[msg.sender][usr] = wad; //injected TRANSACTION ORDER DEPENDENCE emit Approval(msg.sender, usr, wad); return true; } // --- Alias --- function push(address usr, uint wad) external { transferFrom(msg.sender, usr, wad); } function pull(address usr, uint wad) external { transferFrom(usr, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) )); require(holder != address(0), "Dai/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit"); require(expiry == 0 || now <= expiry, "Dai/permit-expired"); require(nonce == nonces[holder]++, "Dai/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; allowance[holder][spender] = wad; emit Approval(holder, spender, wad); } } // File: contracts/lib/AddressUtils.sol // Taken from // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol pragma solidity 0.5.8; /** * @dev Collection of functions related to the address type */ library AddressUtils { /** * @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); } } // File: contracts/ReserveBank.sol pragma solidity 0.5.8; /* Note, in Everest V1, the Reserve Bank is not upgradeable. * What will be done is when Everest V2 is deployed, all the tokens * stored in the Reserve Bank will be transferred to the new Reserve Bank. * The new Reverse Bank is likely to be upgradeable, and have more functionality. * However, the ownership of ReserveBank can still be transferred by the Everest owner * * Also, when the switch over happens from V1 to V2, it is okay the empty the reserve bank right * away. This is because all existing challenges will fail on V1, since Everest V1 will no * longer be the owner of the Registry, and any challenge will not be able to withdraw * from the Reserve Bank. */ contract ReserveBank is Ownable { using SafeMath for uint256; using AddressUtils for address; Dai public token; constructor(address _daiAddress) public { require(_daiAddress.isContract(), "The address should be a contract"); token = Dai(_daiAddress); } /** @dev Allow the owner of the contract (Everest) to withdraw the funds. @param _receiver The address receiving the tokens @param _amount The amount being withdrawn @return True if successful */ function withdraw(address _receiver, uint256 _amount) external onlyOwner returns (bool) { require(_receiver != address(0), "Receiver must not be 0 address"); return token.transfer(_receiver, _amount); } } // File: contracts/Registry.sol pragma solidity 0.5.8; contract Registry is Ownable { // ------ // STATE // ------ struct Member { uint256 challengeID; uint256 memberStartTime; // Used for voting: voteWeight = sqrt(now - memberStartTime) } // Note, this address is used to map to the owner and delegates in the ERC-1056 registry mapping(address => Member) public members; // ----------------- // GETTER FUNCTIONS // ----------------- /** @dev Get the challenge ID of a Member. If no challenge exists it returns 0 @param _member The member being checked @return The challengeID */ function getChallengeID(address _member) external view returns (uint256) { require(_member != address(0), "Can't check 0 address"); Member memory member = members[_member]; return member.challengeID; } /** @dev Get the start time of a Member. If no time exists it returns 0 @param _member The member being checked @return The start time */ function getMemberStartTime(address _member) external view returns (uint256) { require(_member != address(0), "Can't check 0 address"); Member memory member = members[_member]; return member.memberStartTime; } // ----------------- // SETTER FUNCTIONS // ----------------- /** @dev Set a member in the Registry. Only Everest can call this function. @param _member The member being added @return The start time of the member */ function setMember(address _member) external onlyOwner returns (uint256) { require(_member != address(0), "Can't check 0 address"); Member memory member = Member({ challengeID: 0, /* solium-disable-next-line security/no-block-members*/ memberStartTime: now }); members[_member] = member; /* solium-disable-next-line security/no-block-members*/ return now; } /** @dev Edit the challengeID. Can be used to set a challenge or remove a challenge for a member. Only Everest can call. @param _member The member being checked @param _newChallengeID The new challenge ID. Pass in 0 to remove a challenge. */ function editChallengeID(address _member, uint256 _newChallengeID) external onlyOwner { require(_member != address(0), "Can't check 0 address"); Member storage member = members[_member]; member.challengeID = _newChallengeID; } /** @dev Remove a member. Only Everest can call @param _member The member being removed */ function deleteMember(address _member) external onlyOwner { require(_member != address(0), "Can't check 0 address"); delete members[_member]; } } // File: contracts/lib/EthereumDIDRegistry.sol /* Original Author: https://github.com/uport-project/ethr-did-registry Pragma has been changed for this document from what is deployed on mainnet. This shouldn"t pose a problem, but it means a lot of syntax has been changed. This contract is only used for testing. On mainnet, we will use the existing DID registry: https://etherscan.io/address/0xdca7ef03e98e0dc2b855be647c39abe984fcf21b#code This contract is also deployed on all testnets, which can be found here: https://github.com/uport-project/ethr-did-registry This contract is included in this repository for testing purposes on ganache. For deploying to testnets or mainnet, it will never be included in the deploy script, since we will use the deployed versions in the above link. */ pragma solidity 0.5.8; contract EthereumDIDRegistry { mapping(address => address) public owners; mapping(address => mapping(bytes32 => mapping(address => uint256))) public delegates; mapping(address => uint256) public changed; mapping(address => uint256) public nonce; modifier onlyOwner(address identity, address actor) { require(actor == identityOwner(identity), "Caller must be the identity owner"); _; } event DIDOwnerChanged(address indexed identity, address owner, uint256 previousChange); event DIDDelegateChanged( address indexed identity, bytes32 delegateType, address delegate, uint256 validTo, uint256 previousChange ); event DIDAttributeChanged( address indexed identity, bytes32 name, bytes value, uint256 validTo, uint256 previousChange ); function identityOwner(address identity) public view returns (address) { address owner = owners[identity]; if (owner != address(0)) { return owner; } return identity; } function checkSignature(address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 hash) internal returns (address) { address signer = ecrecover(hash, sigV, sigR, sigS); require(signer == identityOwner(identity), "Signer must be the identity owner"); nonce[signer]++; return signer; } function validDelegate(address identity, bytes32 delegateType, address delegate) public view returns (bool) { uint256 validity = delegates[identity][keccak256(abi.encode(delegateType))][delegate]; /* solium-disable-next-line security/no-block-members*/ return (validity > now); } function changeOwner(address identity, address actor, address newOwner) internal onlyOwner(identity, actor) { owners[identity] = newOwner; emit DIDOwnerChanged(identity, newOwner, changed[identity]); changed[identity] = block.number; } function changeOwner(address identity, address newOwner) public { changeOwner(identity, msg.sender, newOwner); } function changeOwnerSigned( address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, address newOwner ) public { bytes32 hash = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0), this, nonce[identityOwner(identity)], identity, "changeOwner", newOwner ) ); changeOwner(identity, checkSignature(identity, sigV, sigR, sigS, hash), newOwner); } function addDelegate( address identity, address actor, bytes32 delegateType, address delegate, uint256 validity ) internal onlyOwner(identity, actor) { /* solium-disable-next-line security/no-block-members*/ delegates[identity][keccak256(abi.encode(delegateType))][delegate] = now + validity; emit DIDDelegateChanged( identity, delegateType, delegate, /* solium-disable-next-line security/no-block-members*/ now + validity, changed[identity] ); changed[identity] = block.number; } function addDelegate(address identity, bytes32 delegateType, address delegate, uint256 validity) public { addDelegate(identity, msg.sender, delegateType, delegate, validity); } function addDelegateSigned( address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 delegateType, address delegate, uint256 validity ) public { bytes32 hash = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0), this, nonce[identityOwner(identity)], identity, "addDelegate", delegateType, delegate, validity ) ); addDelegate( identity, checkSignature(identity, sigV, sigR, sigS, hash), delegateType, delegate, validity ); } function revokeDelegate(address identity, address actor, bytes32 delegateType, address delegate) internal onlyOwner(identity, actor) { /* solium-disable-next-line security/no-block-members*/ delegates[identity][keccak256(abi.encode(delegateType))][delegate] = now; /* solium-disable-next-line security/no-block-members*/ emit DIDDelegateChanged(identity, delegateType, delegate, now, changed[identity]); changed[identity] = block.number; } function revokeDelegate(address identity, bytes32 delegateType, address delegate) public { revokeDelegate(identity, msg.sender, delegateType, delegate); } function revokeDelegateSigned( address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 delegateType, address delegate ) public { bytes32 hash = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0), this, nonce[identityOwner(identity)], identity, "revokeDelegate", delegateType, delegate ) ); revokeDelegate( identity, checkSignature(identity, sigV, sigR, sigS, hash), delegateType, delegate ); } function setAttribute( address identity, address actor, bytes32 name, bytes memory value, uint256 validity ) internal onlyOwner(identity, actor) { /* solium-disable-next-line security/no-block-members*/ emit DIDAttributeChanged(identity, name, value, now + validity, changed[identity]); changed[identity] = block.number; } function setAttribute(address identity, bytes32 name, bytes memory value, uint256 validity) public { setAttribute(identity, msg.sender, name, value, validity); } function setAttributeSigned( address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 name, bytes memory value, uint256 validity ) public { bytes32 hash = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0), this, nonce[identityOwner(identity)], identity, "setAttribute", name, value, validity ) ); setAttribute( identity, checkSignature(identity, sigV, sigR, sigS, hash), name, value, validity ); } function revokeAttribute(address identity, address actor, bytes32 name, bytes memory value) internal onlyOwner(identity, actor) { emit DIDAttributeChanged(identity, name, value, 0, changed[identity]); changed[identity] = block.number; } function revokeAttribute(address identity, bytes32 name, bytes memory value) public { revokeAttribute(identity, msg.sender, name, value); } function revokeAttributeSigned( address identity, uint8 sigV, bytes32 sigR, bytes32 sigS, bytes32 name, bytes memory value ) public { bytes32 hash = keccak256( abi.encodePacked( bytes1(0x19), bytes1(0), this, nonce[identityOwner(identity)], identity, "revokeAttribute", name, value ) ); revokeAttribute(identity, checkSignature(identity, sigV, sigR, sigS, hash), name, value); } } // File: contracts/abdk-libraries-solidity/ABDKMath64x64.sol /* * TheGraph is using this software as described in the README.md in this folder * https://github.com/abdk-consulting/abdk-libraries-solidity/tree/939f0a264f2d07a9e2c7a3a020f0db2c0885dc01 * * This library has been significantly reduced to only include the functions needed for Everest * Please visit the library at the link above for more details */ /* * ABDK Math 64.64 Smart Contract Library. Copyright 1 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.5.8; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // File: contracts/Everest.sol /* Everest is a DAO that is designed to curate a Registry of members. This storage of the list is in Registry. The EthereumDIDRegistry is used to store data such as attributes and delegates and transfer of ownership. The only storage in the Everest contract is Challenges and Votes, which can be safely removed upon completion. This allows for Everest to be an upgradeable contract, while Registry is the persistent storage. The DAO is inspired by the Moloch DAO smart contracts https://github.com/MolochVentures/moloch */ pragma solidity 0.5.8; contract Everest is Ownable { using SafeMath for uint256; using ABDKMath64x64 for uint256; using ABDKMath64x64 for int128; using AddressUtils for address; // ----------------- // STATE // ----------------- // Voting period length for a challenge (in unix seconds) uint256 public votingPeriodDuration; // Deposit that must be made in order to submit a challenge uint256 public challengeDeposit; // Application fee to become a member uint256 public applicationFee; // IPFS hash for off chain storage of the Everest Charter bytes32 public charter; // IPFS hash for off chain storage of the Everest Categories bytes32 public categories; // Challenge freeze that can prevent new challenges from being made bool public challengesFrozen; // Approved token contract reference (i.e. DAI) Dai public approvedToken; // Reserve bank contract reference ReserveBank public reserveBank; // ERC-1056 contract reference EthereumDIDRegistry public erc1056Registry; // Registry contract reference Registry public registry; // We pass in the bytes representation of the string 'everest' // bytes("everest") = 0x65766572657374. Then add 50 zeros to the end. The bytes32 value // is passed to the ERC-1056 registry, and hashed within the delegate functions bytes32 constant delegateType = 0x6576657265737400000000000000000000000000000000000000000000000000; mapping (uint256 => Challenge) public challenges; // Challenge counter for challenge IDs. With upgrading the contract, the latest challengeID // must be the last challengeID + 1 of the old version of Everest uint256 public challengeCounter; // ------- // EVENTS // ------- // Event data on delegates, owner, and offChainData are emitted from the ERC-1056 registry event NewMember(address indexed member, uint256 startTime, uint256 fee); event MemberExited(address indexed member); event CharterUpdated(bytes32 indexed data); event CategoriesUpdated(bytes32 indexed data); event Withdrawal(address indexed receiver, uint256 amount); event VotingDurationUpdated(uint256 indexed duration); event ChallengeDepositUpdated(uint256 indexed deposit); event ApplicationFeeUpdated(uint256 indexed fee); event ChallengesFrozen(bool isFrozen); event EverestDeployed( address owner, address approvedToken, uint256 votingPeriodDuration, uint256 challengeDeposit, uint256 applicationFee, bytes32 charter, bytes32 categories, address didRegistry, address reserveBank, address registry, uint256 startingChallengeID ); event MemberChallenged( address indexed member, uint256 indexed challengeID, address indexed challenger, uint256 challengeEndTime, bytes32 details ); event SubmitVote( uint256 indexed challengeID, address indexed submitter, // i.e. msg.sender address indexed votingMember, VoteChoice voteChoice, uint256 voteWeight ); event ChallengeFailed( address indexed member, uint256 indexed challengeID, uint256 yesVotes, uint256 noVotes, uint256 voterCount, uint256 resolverReward ); event ChallengeSucceeded( address indexed member, uint256 indexed challengeID, uint256 yesVotes, uint256 noVotes, uint256 voterCount, uint256 challengerReward, uint256 resolverReward ); // ------ // STATE // ------ enum VoteChoice { Null, // Same as not voting at all (i.e. 0 value) Yes, No } struct Challenge { address challenger; // The member who submitted the challenge address challengee; // The member being challenged uint256 yesVotes; // The total weight of YES votes for this challenge uint256 noVotes; // The total weight of NO votes for this challenge uint256 voterCount; // Total count of voters participating in the challenge uint256 endTime; // Ending time of the challenge bytes32 details; // Challenge details - an IPFS hash, without Qm, to make bytes32 mapping (address => VoteChoice) voteChoiceByMember; // The choice by each member mapping (address => uint256) voteWeightByMember; // The vote weight of each member } // ---------- // MODIFIERS // ---------- /** @dev Modifer that allows a function to be called by the owner or delegate of a member. @param _member Member interacting with everest */ modifier onlyMemberOwnerOrDelegate(address _member) { require( isMember(_member), "onlyMemberOwnerOrDelegate - Address is not a Member" ); address memberOwner = erc1056Registry.identityOwner(_member); bool validDelegate = erc1056Registry.validDelegate(_member, delegateType, msg.sender); require( validDelegate || memberOwner == msg.sender, "onlyMemberOwnerOrDelegate - Caller must be delegate or owner" ); _; } /** @dev Modifer that allows a function to be called by owner of a member. Only the member can call (no delegate permissions) @param _member Member interacting with everest */ modifier onlyMemberOwner(address _member) { require( isMember(_member), "onlyMemberOwner - Address is not a member" ); address memberOwner = erc1056Registry.identityOwner(_member); require( memberOwner == msg.sender, "onlyMemberOwner - Caller must be the owner" ); _; } // ---------- // FUNCTIONS // ---------- constructor( address _approvedToken, uint256 _votingPeriodDuration, uint256 _challengeDeposit, uint256 _applicationFee, bytes32 _charter, bytes32 _categories, address _DIDregistry, address _reserveBank, address _registry, uint256 _startingChallengeID ) public { require(_approvedToken.isContract(), "The _approvedToken address should be a contract"); require(_DIDregistry.isContract(), "The _DIDregistry address should be a contract"); require(_reserveBank.isContract(), "The _reserveBank address should be a contract"); require(_registry.isContract(), "The _registry address should be a contract"); require(_votingPeriodDuration > 0, "constructor - _votingPeriodDuration cannot be 0"); require(_challengeDeposit > 0, "constructor - _challengeDeposit cannot be 0"); require(_applicationFee > 0, "constructor - _applicationFee cannot be 0"); require(_startingChallengeID != 0, "constructor - _startingChallengeID cannot be 0"); approvedToken = Dai(_approvedToken); votingPeriodDuration = _votingPeriodDuration; challengeDeposit = _challengeDeposit; applicationFee = _applicationFee; charter = _charter; categories = _categories; erc1056Registry = EthereumDIDRegistry(_DIDregistry); reserveBank = ReserveBank(_reserveBank); registry = Registry(_registry); challengeCounter = _startingChallengeID; emit EverestDeployed( msg.sender, // i.e owner _approvedToken, _votingPeriodDuration, _challengeDeposit, _applicationFee, _charter, _categories, _DIDregistry, _reserveBank, _registry, _startingChallengeID ); } // --------------------- // ADD MEMBER FUNCTIONS // --------------------- /** @dev Allows a user to add a member to the Registry and add off chain data to the DID registry. The sig for changeOwner() and setAttribute() are from _newMember and for DAIS permit() it is the _owner. [0] = setAttributeSigned() signature [1] = changeOwnerSigned() signature [2] = permit() signature @param _newMember The address of the new member @param _sigV V of sigs @param _sigR R of sigs @param _sigS S of sigs @param _memberOwner Owner of the member (on the DID registry) @param _offChainDataName Attribute name. Should be a string less than 32 bytes, converted to bytes32. example: 'ProjectData' = 0x50726f6a65637444617461, with zeros appended to make it 32 bytes @param _offChainDataValue Attribute data stored offchain (IPFS) @param _offChainDataValidity Length of time attribute data is valid (unix) */ function applySignedWithAttributeAndPermit( address _newMember, uint8[3] calldata _sigV, bytes32[3] calldata _sigR, bytes32[3] calldata _sigS, address _memberOwner, bytes32 _offChainDataName, bytes calldata _offChainDataValue, uint256 _offChainDataValidity ) external { require(_newMember != address(0), "Member can't be 0 address"); require(_memberOwner != address(0), "Owner can't be 0 address"); applySignedWithAttributeAndPermitInternal( _newMember, _sigV, _sigR, _sigS, _memberOwner, _offChainDataName, _offChainDataValue, _offChainDataValidity ); } /// @dev Note that this internal function is created in order to avoid the /// Solidity stack too deep error. function applySignedWithAttributeAndPermitInternal( address _newMember, uint8[3] memory _sigV, bytes32[3] memory _sigR, bytes32[3] memory _sigS, address _memberOwner, bytes32 _offChainDataName, bytes memory _offChainDataValue, uint256 _offChainDataValidity ) internal { // Approve Everest to transfer DAI on the owner's behalf // Expiry = 0 is infinite. true is unlimited allowance uint256 nonce = approvedToken.nonces(_memberOwner); approvedToken.permit(_memberOwner, address(this), nonce, 0, true, _sigV[2], _sigR[2], _sigS[2]); applySignedWithAttribute( _newMember, [_sigV[0], _sigV[1]], [_sigR[0], _sigR[1]], [_sigS[0], _sigS[1]], _memberOwner, _offChainDataName, _offChainDataValue, _offChainDataValidity ); } /** @dev Functions the same as applySignedWithAttributeAndPermit(), except without permit(). This function should be called by any _owner that has already called permit() for Everest. [0] = setAttributeSigned() signature [1] = changeOwnerSigned() signature @param _newMember The address of the new member @param _sigV V of sigs @param _sigR R of sigs @param _sigS S of sigs @param _memberOwner Owner of the member application @param _offChainDataName Attribute name. Should be a string less than 32 bytes, converted to bytes32. example: 'ProjectData' = 0x50726f6a65637444617461, with zeros appended to make it 32 bytes @param _offChainDataValue Attribute data stored offchain (IPFS) @param _offChainDataValidity Length of time attribute data is valid */ function applySignedWithAttribute( address _newMember, uint8[2] memory _sigV, bytes32[2] memory _sigR, bytes32[2] memory _sigS, address _memberOwner, bytes32 _offChainDataName, bytes memory _offChainDataValue, uint256 _offChainDataValidity ) public { require(_newMember != address(0), "Member can't be 0 address"); require(_memberOwner != address(0), "Owner can't be 0 address"); require( registry.getMemberStartTime(_newMember) == 0, "applySignedInternal - This member already exists" ); uint256 startTime = registry.setMember(_newMember); // This event should be emitted before changeOwnerSigned() is called. This way all events // in the Ethereum DID registry can start to be considered within the bounds of the event // event NewMember() and the end of membership with event MemberExit() or event // ChallengeSucceeded() emit NewMember( _newMember, startTime, applicationFee ); erc1056Registry.setAttributeSigned( _newMember, _sigV[0], _sigR[0], _sigS[0], _offChainDataName, _offChainDataValue, _offChainDataValidity ); erc1056Registry.changeOwnerSigned(_newMember, _sigV[1], _sigR[1], _sigS[1], _memberOwner); // Transfers tokens from owner to the reserve bank require( approvedToken.transferFrom(_memberOwner, address(reserveBank), applicationFee), "applySignedInternal - Token transfer failed" ); } /** @dev Allow a member to voluntarily leave. Note that this does not reset ownership or delegates in the ERC-1056 registry. This must be done by calling the respective functions in the registry that handle those. @param _member Member exiting the list */ function memberExit( address _member ) external onlyMemberOwner(_member) { require(_member != address(0), "Member can't be 0 address"); require( !memberChallengeExists(_member), "memberExit - Can't exit during ongoing challenge" ); registry.deleteMember(_member); emit MemberExited(_member); } // -------------------- // CHALLENGE FUNCTIONS // -------------------- /** @dev Starts a challenge on a member. Challenger deposits a fee. @param _challenger The address of the member who is challenging another member @param _challengee The address of the member being challenged @param _details Extra details relevant to the challenge. (IPFS hash without Qm) @return Challenge ID for the created challenge */ function challenge( address _challenger, address _challengee, bytes32 _details ) external onlyMemberOwner(_challenger) returns (uint256 challengeID) { require(_challenger != address(0), "Challenger can't be 0 address"); require(isMember(_challengee), "challenge - Challengee must exist"); require( _challenger != _challengee, "challenge - Can't challenge self" ); require(challengesFrozen != true, "challenge - Cannot create challenge, frozen"); uint256 currentChallengeID = registry.getChallengeID(_challengee); require(currentChallengeID == 0, "challenge - Existing challenge must be resolved first"); uint256 newChallengeID = challengeCounter; Challenge memory newChallenge = Challenge({ challenger: _challenger, challengee: _challengee, // It is okay to start counts at 0 here. submitVote() is called at the end of the func yesVotes: 0, noVotes: 0, voterCount: 0, /* solium-disable-next-line security/no-block-members*/ endTime: now.add(votingPeriodDuration), details: _details }); challengeCounter = challengeCounter.add(1); challenges[newChallengeID] = newChallenge; // Updates member to store most recent challenge registry.editChallengeID(_challengee, newChallengeID); // Transfer tokens from challenger to reserve bank require( approvedToken.transferFrom(msg.sender, address(reserveBank), challengeDeposit), "challenge - Token transfer failed" ); emit MemberChallenged( _challengee, newChallengeID, _challenger, /* solium-disable-next-line security/no-block-members*/ now.add(votingPeriodDuration), newChallenge.details ); // Add challengers' vote into the challenge submitVote(newChallengeID, VoteChoice.Yes, _challenger); return newChallengeID; } /** @dev Submit a vote. Owner or delegate can submit @param _challengeID The challenge ID @param _voteChoice The vote choice (yes or no) @param _votingMember The member who is voting */ function submitVote( uint256 _challengeID, VoteChoice _voteChoice, address _votingMember ) public onlyMemberOwnerOrDelegate(_votingMember) { require(_votingMember != address(0), "Member can't be 0 address"); require( _voteChoice == VoteChoice.Yes || _voteChoice == VoteChoice.No, "submitVote - Vote must be either Yes or No" ); Challenge storage storedChallenge = challenges[_challengeID]; require( storedChallenge.endTime > 0, "submitVote - Challenge does not exist" ); require( !hasVotingPeriodExpired(storedChallenge.endTime), "submitVote - Challenge voting period has expired" ); require( storedChallenge.voteChoiceByMember[_votingMember] == VoteChoice.Null, "submitVote - Member has already voted on this challenge" ); require( storedChallenge.challengee != _votingMember, "submitVote - Member can't vote on their own challenge" ); uint256 startTime = registry.getMemberStartTime(_votingMember); // The lower the member start time (i.e. the older the member) the more vote weight uint256 voteWeightSquared = storedChallenge.endTime.sub(startTime); // Here we use ABDKMath64x64 to do the square root of the vote weight // We have to covert it to a 64.64 fixed point number, do sqrt(), then convert it // back to uint256. uint256 wraps the result of toUInt(), since it returns uint64 int128 sixtyFourBitFPInt = voteWeightSquared.fromUInt(); int128 voteWeightInt128 = sixtyFourBitFPInt.sqrt(); uint256 voteWeight = uint256(voteWeightInt128.toUInt()); // Store vote with _votingMember, not msg.sender, since a delegate can vote storedChallenge.voteChoiceByMember[_votingMember] = _voteChoice; storedChallenge.voteWeightByMember[_votingMember] = voteWeight; storedChallenge.voterCount = storedChallenge.voterCount.add(1); // Count vote if (_voteChoice == VoteChoice.Yes) { storedChallenge.yesVotes = storedChallenge.yesVotes.add(voteWeight); } else if (_voteChoice == VoteChoice.No) { storedChallenge.noVotes = storedChallenge.noVotes.add(voteWeight); } emit SubmitVote(_challengeID, msg.sender, _votingMember, _voteChoice, voteWeight); } /** @dev Submit many votes from owner or delegate with multiple members they own or are delegates of @param _challengeID The challenge ID @param _voteChoices The vote choices (yes or no) @param _voters The members who are voting */ function submitVotes( uint256 _challengeID, VoteChoice[] calldata _voteChoices, address[] calldata _voters ) external { require( _voteChoices.length == _voters.length, "submitVotes - Arrays must be equal" ); require(_voteChoices.length < 90, "submitVotes - Array should be < 90 to avoid going over the block gas limit"); for (uint256 i; i < _voteChoices.length; i++){ submitVote(_challengeID, _voteChoices[i], _voters[i]); } } /** @dev Resolve a challenge A successful challenge means the member is removed. Anyone can call this function. They will be rewarded with 1/10 of the challenge deposit. @param _challengeID The challenge ID */ function resolveChallenge(uint256 _challengeID) external { challengeCanBeResolved(_challengeID); Challenge storage storedChallenge = challenges[_challengeID]; bool didPass = storedChallenge.yesVotes > storedChallenge.noVotes; bool moreThanOneVote = storedChallenge.voterCount > 1; // Challenge reward is 1/10th the challenge deposit. This allows incentivization to // always resolve the challenge for the user that calls this function uint256 challengeRewardDivisor = 10; uint256 resolverReward = challengeDeposit.div(challengeRewardDivisor); if (didPass && moreThanOneVote) { address challengerOwner = erc1056Registry.identityOwner(storedChallenge.challenger); // The amount includes the applicationFee, which is the reward for challenging a project // and getting it successfully removed. Minus the resolver reward uint256 challengerReward = challengeDeposit.add(applicationFee).sub(resolverReward); require( reserveBank.withdraw(challengerOwner, challengerReward), "resolveChallenge - Rewarding challenger failed" ); // Transfer resolver reward require( reserveBank.withdraw(msg.sender, resolverReward), "resolveChallenge - Rewarding resolver failed" ); registry.deleteMember(storedChallenge.challengee); emit ChallengeSucceeded( storedChallenge.challengee, _challengeID, storedChallenge.yesVotes, storedChallenge.noVotes, storedChallenge.voterCount, challengerReward, resolverReward ); } else { // Transfer resolver reward require( reserveBank.withdraw(msg.sender, resolverReward), "resolveChallenge - Rewarding resolver failed" ); // Remove challenge ID from the Member in the registry registry.editChallengeID(storedChallenge.challengee, 0); emit ChallengeFailed( storedChallenge.challengee, _challengeID, storedChallenge.yesVotes, storedChallenge.noVotes, storedChallenge.voterCount, resolverReward ); } // Delete challenge from Everest in either case delete challenges[_challengeID]; } // ------------------------ // EVEREST OWNER FUNCTIONS // ------------------------ /** @dev Allows the owner of everest to withdraw funds from the reserve bank. @param _receiver The address receiving funds @param _amount The amount of funds being withdrawn @return True if withdrawal is successful */ function withdraw(address _receiver, uint256 _amount) external onlyOwner returns (bool) { require(_receiver != address(0), "Receiver must not be 0 address"); require(_amount > 0, "Amount must be greater than 0"); emit Withdrawal(_receiver, _amount); return reserveBank.withdraw(_receiver, _amount); } /** @dev Allows the owner of Everest to transfer the ownership of ReserveBank @param _newOwner The new owner */ function transferOwnershipReserveBank(address _newOwner) external onlyOwner { reserveBank.transferOwnership(_newOwner); } /** @dev Allows the owner of Everest to transfer the ownership of Registry @param _newOwner The new owner */ function transferOwnershipRegistry(address _newOwner) external onlyOwner { registry.transferOwnership(_newOwner); } /** @dev Updates the charter for Everest @param _newCharter The data that point to the new charter */ function updateCharter(bytes32 _newCharter) external onlyOwner { charter = _newCharter; emit CharterUpdated(charter); } /** @dev Updates the categories for Everest @param _newCategories The data that point to the new categories */ function updateCategories(bytes32 _newCategories) external onlyOwner { categories = _newCategories; emit CategoriesUpdated(categories); } /** @dev Updates the voting duration for Everest @param _newVotingDuration New voting duration in unix seconds */ function updateVotingPeriodDuration(uint256 _newVotingDuration) external onlyOwner { votingPeriodDuration = _newVotingDuration; emit VotingDurationUpdated(votingPeriodDuration); } /** @dev Updates the challenge deposit required @param _newDeposit The new value for the challenge deposit, with decimals (10^18) */ function updateChallengeDeposit(uint256 _newDeposit) external onlyOwner { challengeDeposit = _newDeposit; emit ChallengeDepositUpdated(challengeDeposit); } /** @dev Updates the application fee for Everest @param _newFee The new application fee, with decimals (10^18) */ function updateApplicationFee(uint256 _newFee) external onlyOwner { applicationFee = _newFee; emit ApplicationFeeUpdated(applicationFee); } /** @dev Freezes the ability to create challenges @param _isFrozen Pass in true if challenges are to be frozen */ function updateChallengeFreeze(bool _isFrozen) external onlyOwner { challengesFrozen = _isFrozen; emit ChallengesFrozen(challengesFrozen); } // ----------------- // GETTER FUNCTIONS // ----------------- /** @dev Returns true if a challenge vote period has finished @param _endTime The starting period of the challenge @return True if voting period has expired */ function hasVotingPeriodExpired(uint256 _endTime) private view returns (bool) { /* solium-disable-next-line security/no-block-members*/ return now >= _endTime; } /** @dev Returns true if the address is a member @param _member The member name of the member whose status is to be examined @return True is address is a member */ function isMember(address _member) public view returns (bool){ require(_member != address(0), "Member can't be 0 address"); uint256 startTime = registry.getMemberStartTime(_member); if (startTime > 0){ return true; } return false; } /** @dev Returns true if the member has an unresolved challenge. False if the challenge does not exist. @param _member The member that is being checked for a challenge. @return True if a challenge exists on the member */ function memberChallengeExists(address _member) public view returns (bool) { require(_member != address(0), "Member can't be 0 address"); uint256 challengeID = registry.getChallengeID(_member); return (challengeID > 0); } /** @dev Determines whether voting has concluded in a challenge for a given member. Throws if challenge can't be resolved @param _challengeID The challenge ID */ function challengeCanBeResolved(uint256 _challengeID) private view { Challenge storage storedChallenge = challenges[_challengeID]; require( challenges[_challengeID].endTime > 0, "challengeCanBeResolved - Challenge does not exist or was completed" ); require( hasVotingPeriodExpired(storedChallenge.endTime), "challengeCanBeResolved - Current challenge is not ready to be resolved" ); } }
Challenge details - an IPFS hash, without Qm, to make bytes32
bytes32 details;
1,810,604
[ 1, 18359, 3189, 300, 392, 2971, 4931, 1651, 16, 2887, 2238, 81, 16, 358, 1221, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1731, 1578, 3189, 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, -100 ]
pragma solidity ^0.4.24; contract PriceOracleInterface { /** * @notice Gets the price of a given asset * @dev fetches the price of a given asset * @param asset Asset to get the price of * @return the price scaled by 10**18, or zero if the price is not available */ function assetPrices(address asset) public view returns (uint); } contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(Error.OPAQUE_ERROR), uint(info), opaqueError); return uint(Error.OPAQUE_ERROR); } } contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate(address asset, uint cash, uint borrows) public view returns (uint, uint); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate(address asset, uint cash, uint borrows) public view returns (uint, uint); } contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint a, uint b) internal pure returns (Error, uint) { if (a == 0) { return (Error.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (Error, uint) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (Error, uint) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint a, uint b) internal pure returns (Error, uint) { uint c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub(uint a, uint b, uint c) internal pure returns (Error, uint) { (Error err0, uint sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address asset, address from, uint amount) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address asset, address from, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address asset, address to, uint amount) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } contract Exponential is ErrorReporter, CarefulMath { // TODO: We may wish to put the result of 10**18 here instead of the expression. // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint constant expScale = 10**18; // See TODO on expScale uint constant halfExpScale = expScale/2; struct Exp { uint mantissa; } uint constant mantissaOne = 10**18; uint constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (Error, Exp memory) { (Error err0, uint scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error error, uint result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (Error, Exp memory) { (Error err0, uint descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp divisor) pure internal returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { (Error err0, uint doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint doubleScaledProductWithHalfScale) = add(halfExpScale, doubleScaledProduct); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint product) = div(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / 10**18; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; //TODO: Add some simple tests and this in another PR yo. } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract MoneyMarket is Exponential, SafeToken { uint constant initialInterestIndex = 10 ** 18; uint constant defaultOriginationFee = 0; // default is zero bps uint constant minimumCollateralRatioMantissa = 11 * (10 ** 17); // 1.1 uint constant maximumLiquidationDiscountMantissa = (10 ** 17); // 0.1 /** * @notice `MoneyMarket` is the core Compound MoneyMarket contract */ constructor() public { admin = msg.sender; collateralRatio = Exp({mantissa: 2 * mantissaOne}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: 0}); // oracle must be configured via _setOracle } /** * @notice Do not pay directly into MoneyMarket, please use `supply`. */ function() payable public { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address public oracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = the total interestIndex as calculated after applying the customer's most recent balance-changing action * } */ struct Balance { uint principal; uint interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint blockNumber; InterestRateModel interestRateModel; uint totalSupply; uint supplyRateMantissa; uint supplyIndex; uint totalBorrows; uint borrowRateMantissa; uint borrowIndex; } /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken(address account, address asset, uint amount, uint startingBalance, uint borrowAmountWithFee, uint newBalance); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid(address account, address asset, uint amount, uint startingBalance, uint newBalance); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) */ event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); /** * @dev emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @dev newOracle - address of new oracle */ event NewOracle(address oldOracle, address newOracle); /** * @dev emitted when new market is supported by admin */ event SupportedMarket(address asset, address interestRateModel); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters(uint oldCollateralRatioMantissa, uint newCollateralRatioMantissa, uint oldLiquidationDiscountMantissa, uint newLiquidationDiscountMantissa); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee(uint oldOriginationFeeMantissa, uint newOriginationFeeMantissa); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel(address asset, address interestRateModel); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner); /** * @dev emitted when a supported market is suspended by admin */ event SuspendedMarket(address asset); /** * @dev emitted when admin either pauses or resumes the contract; newState is the resulting state */ event SetPaused(bool newState); /** * @dev Simple function to calculate min between two numbers. */ function min(uint a, uint b) pure internal returns (uint) { if (a < b) { return a; } else { return b; } } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint) { return collateralMarkets.length; } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` */ function calculateInterestIndex(uint startingInterestIndex, uint interestRateMantissa, uint blockStart, uint blockEnd) pure internal returns (Error, uint) { // Get the block delta (Error err0, uint blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar(Exp({mantissa: interestRateMantissa}), blockDelta); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp(blocksTimesRate, Exp({mantissa: mantissaOne})); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar(onePlusBlocksTimesRate, startingInterestIndex); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * * TODO: Is there a way to handle this that is less likely to overflow? */ function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. */ function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` */ function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * * TODO: Track at what magnitude this fee rounds down to zero? */ function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne})); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (oracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } PriceOracleInterface oracleInterface = PriceOracleInterface(oracle); uint priceMantissa = oracleInterface.assetPrices(asset); return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller = pendingAdmin // msg.sender can't be zero if (msg.sender != pendingAdmin) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint(Error.NO_ERROR); } /** * @notice Set new oracle, who can set asset prices * @dev Admin function to change oracle * @param newOracle New oracle address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOracle(address newOracle) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK); } // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle); oracleInterface.assetPrices(address(0)); address oldOracle = oracle; // Store oracle = newOracle oracle = newOracle; emit NewOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice set `paused` to the specified state * @dev Admin function to pause or resume the market * @param requestedState value to assign to `paused` * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPaused(bool requestedState) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSED_OWNER_CHECK); } paused = requestedState; emit SetPaused(requestedState); return uint(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int) { (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account); require(err == Error.NO_ERROR); if (isZeroExp(accountLiquidity)) { return -1 * int(truncate(accountShortfall)); } else { return int(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) view public returns (uint) { Error err; uint newSupplyIndex; uint userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex); require(err == Error.NO_ERROR); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) view public returns (uint) { Error err; uint newBorrowIndex; uint userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex); require(err == Error.NO_ERROR); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use with Compound * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use with Compound. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK); } // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; emit SuspendedMarket(asset); return uint(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters(uint collateralRatioMantissa, uint liquidationDiscountMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RISK_PARAMETERS_OWNER_CHECK); } Exp memory newCollateralRatio = Exp({mantissa: collateralRatioMantissa}); Exp memory newLiquidationDiscount = Exp({mantissa: liquidationDiscountMantissa}); Exp memory minimumCollateralRatio = Exp({mantissa: minimumCollateralRatioMantissa}); Exp memory maximumLiquidationDiscount = Exp({mantissa: maximumLiquidationDiscountMantissa}); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail(Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail(Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp(newLiquidationDiscount, Exp({mantissa: mantissaOne})); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if (lessThanOrEqualExp(newCollateralRatio, newLiquidationDiscountPlusOne)) { return fail(Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters(oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the origination fee (which is a multiplier on new borrows) * @dev Owner function to set the origination fee * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setOriginationFee(uint originationFeeMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK); } // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows) * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows) * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint amount) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK); } // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint cash = getCash(asset); (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED); } //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint(Error.NO_ERROR); // success } /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED); } // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(balance.principal, balance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED); } (err, localResults.userSupplyUpdated) = add(localResults.userSupplyCurrent, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, balance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; emit SupplyReceived(msg.sender, asset, amount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct WithdrawLocalVars { uint withdrawAmount; uint startingBalance; uint newSupplyIndex; uint userSupplyCurrent; uint userSupplyUpdated; uint newTotalSupply; uint currentCash; uint updatedCash; uint newSupplyRateMantissa; uint newBorrowIndex; uint newBorrowRateMantissa; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; uint withdrawCapacity; } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint requestedAmount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED); } Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub(localResults.userSupplyCurrent, localResults.withdrawAmount); if (err != Error.NO_ERROR) { return fail(Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(asset, localResults.withdrawAmount); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfWithdrawal) ) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; emit SupplyWithdrawn(msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, localResults.userSupplyUpdated); return uint(Error.NO_ERROR); // success } struct AccountValueLocalVars { address assetAddress; uint collateralMarketsLength; uint newSupplyIndex; uint userSupplyCurrent; Exp supplyTotalValue; Exp sumSupplies; uint newBorrowIndex; uint userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). */ function calculateAccountLiquidity(address userAddress) internal view returns (Error, Exp memory, Exp memory) { Error err; uint sumSupplyValuesMantissa; uint sumBorrowValuesMantissa; (err, sumSupplyValuesMantissa, sumBorrowValuesMantissa) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return(err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({mantissa: sumSupplyValuesMantissa}); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp(collateralRatio, Exp({mantissa: sumBorrowValuesMantissa})); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) * TODO: Possibly should add a Min(500, collateralMarkets.length) for extra safety * TODO: To help save gas we could think about using the current Market.interestIndex * accumulate interest rather than calculating it */ function calculateAccountValuesInternal(address userAddress) internal view returns (Error, uint, uint) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][localResults.assetAddress]; Balance storage borrowBalance = borrowBalances[userAddress][localResults.assetAddress]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex(currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userSupplyCurrent); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp(localResults.supplyTotalValue, localResults.sumSupplies); if (err != Error.NO_ERROR) { return (err, 0, 0); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex(currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return (err, 0, 0); } // In the case of borrow, we multiply the borrow value by the collateral ratio (err, localResults.borrowTotalValue) = getPriceForAssetAmount(localResults.assetAddress, localResults.userBorrowCurrent); // ( borrowCurrent* oraclePrice * collateralRatio) = borrowTotalValueInEth if (err != Error.NO_ERROR) { return (err, 0, 0); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp(localResults.borrowTotalValue, localResults.sumBorrows); if (err != Error.NO_ERROR) { return (err, 0, 0); } } } return (Error.NO_ERROR, localResults.sumSupplies.mantissa, localResults.sumBorrows.mantissa); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) { (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint(err), 0, 0); } return (0, supplyValue, borrowValue); } struct PayBorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint repayAmount; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED); } PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (amount == uint(-1)) { localResults.repayAmount = min(getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent); } else { localResults.repayAmount = amount; } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub(localResults.userBorrowCurrent, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowRepaid(msg.sender, asset, localResults.repayAmount, localResults.startingBalance, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } struct BorrowLocalVars { uint newBorrowIndex; uint userBorrowCurrent; uint borrowAmountWithFee; uint userBorrowUpdated; uint newTotalBorrows; uint currentCash; uint updatedCash; uint newSupplyIndex; uint newSupplyRateMantissa; uint newBorrowRateMantissa; uint startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint newBorrowIndex_UnderwaterAsset; uint newSupplyIndex_UnderwaterAsset; uint newBorrowIndex_CollateralAsset; uint newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint updatedBorrowBalance_TargetUnderwaterAsset; uint newTotalBorrows_ProtocolUnderwaterAsset; uint startingBorrowBalance_TargetUnderwaterAsset; uint startingSupplyBalance_TargetCollateralAsset; uint startingSupplyBalance_LiquidatorCollateralAsset; uint currentSupplyBalance_TargetCollateralAsset; uint updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint updatedSupplyBalance_LiquidatorCollateralAsset; uint newTotalSupply_ProtocolCollateralAsset; uint currentCash_ProtocolUnderwaterAsset; uint updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint newSupplyRateMantissa_ProtocolUnderwaterAsset; uint newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint discountedBorrowDenominatedCollateral; uint maxCloseableBorrowAmount_TargetUnderwaterAsset; uint closeBorrowAmount_TargetUnderwaterAsset; uint seizeSupplyAmount_TargetCollateralAsset; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address targetAccount, address assetBorrow, address assetCollateral, uint requestedAmountClose) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED); } LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[targetAccount][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[targetAccount][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if(err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset (err, localResults.newBorrowIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (err, localResults.currentBorrowBalance_TargetUnderwaterAsset) = calculateBalance(borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset (err, localResults.newSupplyIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } (err, localResults.currentSupplyBalance_TargetCollateralAsset) = calculateBalance(supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset (err, localResults.currentSupplyBalance_LiquidatorCollateralAsset) = calculateBalance(supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (err, localResults.discountedBorrowDenominatedCollateral) = calculateDiscountedBorrowDenominatedCollateral(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. (err, localResults.discountedRepayToEvenAmount) = calculateDiscountedRepayToEvenAmount(targetAccount, localResults.underwaterAssetPrice); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (requestedAmountClose == uint(-1)) { localResults.closeBorrowAmount_TargetUnderwaterAsset = localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if (localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset) { return fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) (err, localResults.seizeSupplyAmount_TargetCollateralAsset) = calculateAmountSeize(localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into Compound // Fail gracefully if asset is not approved or has insufficient balance err = checkTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows_ProtocolUnderwaterAsset) = addThenSub(borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. (err, localResults.newSupplyIndex_UnderwaterAsset) = calculateInterestIndex(borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET); } (rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getSupplyRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset) = borrowMarket.interestRateModel.getBorrowRate(assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. (err, localResults.newBorrowIndex_CollateralAsset) = calculateInterestIndex(collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert (err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset) = add(localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert (err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferIn(assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } // Save borrow market updates borrowMarket.blockNumber = getBlockNumber(); borrowMarket.totalBorrows = localResults.newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = getBlockNumber(); collateralMarket.totalSupply = localResults.newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults.newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults.newBorrowIndex_CollateralAsset; // Save user updates localResults.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset.principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults.updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults.newBorrowIndex_UnderwaterAsset; localResults.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset.principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults.updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; localResults.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset.principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults.updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults.newSupplyIndex_CollateralAsset; emitLiquidationEvent(localResults); return uint(Error.NO_ERROR); // success } /** * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow` */ function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal { // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); emit BorrowLiquidated(localResults.targetAccount, localResults.assetBorrow, localResults.startingBorrowBalance_TargetUnderwaterAsset, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.updatedBorrowBalance_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.startingSupplyBalance_TargetCollateralAsset, localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset, localResults.updatedSupplyBalance_TargetCollateralAsset); } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. **/ function calculateDiscountedRepayToEvenAmount(address targetAccount, Exp memory underwaterAssetPrice) internal view returns (Error, uint) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio (err, _accountLiquidity, accountShortfall_TargetUser) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp(collateralRatio, liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp(collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne})); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp(underwaterAssetPrice, discountedCollateralRatioMinusOne); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); (err, rawResult) = divExp(accountShortfall_TargetUser, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) */ function calculateDiscountedBorrowDenominatedCollateral(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint supplyCurrent_TargetCollateralAsset) view internal returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar(collateralPrice, supplyCurrent_TargetCollateralAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(onePlusLiquidationDiscount, underwaterAssetPrice); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral **/ function calculateAmountSeize(Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint closeBorrowAmount_TargetUnderwaterAsset) internal view returns (Error, uint) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp(Exp({mantissa: mantissaOne}), liquidationDiscount); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(underwaterAssetPrice, liquidationMultiplier); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar(priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint amount) public returns (uint) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail(Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED); } (err, localResults.userBorrowCurrent) = calculateBalance(borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED); } // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add(localResults.userBorrowCurrent, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub(market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED); } // Check customer liquidity (err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` (err, localResults.ethValueOfBorrowAmountWithFee) = getPriceForAssetAmountMulCollatRatio(asset, localResults.borrowAmountWithFee); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee)) { return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, localResults.newTotalBorrows); if (rateCalculationResultCode != 0) { return failOpaque(FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } // Save market updates market.blockNumber = getBlockNumber(); market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; emit BorrowTaken(msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, localResults.userBorrowUpdated); return uint(Error.NO_ERROR); // success } }
Note: FailureInfo (but not Error) is kept in alphabetical order This is because FailureInfo grows significantly faster, and the order of Error has some meaning, while the order of FailureInfo is entirely arbitrary./
enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE }
2,476,449
[ 1, 8067, 30, 13436, 966, 261, 12885, 486, 1068, 13, 353, 16555, 316, 10877, 1706, 1353, 4202, 1220, 353, 2724, 13436, 966, 314, 3870, 14177, 715, 12063, 16, 471, 4202, 326, 1353, 434, 1068, 711, 2690, 12256, 16, 1323, 326, 1353, 434, 13436, 966, 4202, 353, 21658, 11078, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 13436, 966, 288, 203, 3639, 29749, 67, 15468, 67, 25691, 67, 15468, 67, 10687, 16, 203, 3639, 605, 916, 11226, 67, 21690, 67, 2053, 53, 3060, 4107, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 21690, 67, 15993, 42, 4685, 67, 3670, 17418, 16, 203, 3639, 605, 916, 11226, 67, 31414, 2799, 1506, 6344, 67, 38, 1013, 4722, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 2192, 51, 5321, 67, 2053, 53, 3060, 4107, 67, 15993, 42, 4685, 16, 203, 3639, 605, 916, 11226, 67, 2192, 51, 5321, 67, 4051, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 6067, 2849, 1268, 67, 4066, 20093, 16, 203, 3639, 605, 916, 11226, 67, 12693, 1584, 67, 4400, 67, 21134, 16, 203, 3639, 605, 916, 11226, 67, 12917, 67, 38, 916, 11226, 67, 9199, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 12917, 67, 38, 916, 11226, 67, 24062, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 12917, 67, 13272, 23893, 67, 9199, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 12917, 67, 13272, 23893, 67, 24062, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 12917, 67, 28624, 67, 38, 1013, 4722, 67, 7913, 39, 1506, 2689, 67, 11965, 16, 203, 3639, 605, 916, 11226, 67, 12917, 67, 28624, 67, 38, 916, 11226, 2 ]
pragma solidity ^0.6.0; import "../../mcd/saver_proxy/ExchangeHelper.sol"; import "../../loggers/CompoundLogger.sol"; import "../helpers/CompoundSaverHelper.sol"; /// @title Contract that implements repay/boost functionality contract CompoundSaverProxy is CompoundSaverHelper, ExchangeHelper { /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _data Amount and exchange data for the repay [amount, minPrice, exchangeType, gasCost, 0xPrice] /// @param _addrData Coll/Debt addresses [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _callData 0x calldata info function repay( uint[5] memory _data, // amount, minPrice, exchangeType, gasCost, 0xPrice address[3] memory _addrData, // cCollAddress, cBorrowAddress, exchangeAddress bytes memory _callData ) public payable { enterMarket(_addrData[0], _addrData[1]); address payable user = address(uint160(getUserAddress())); uint maxColl = getMaxCollateral(_addrData[0], address(this)); uint collAmount = (_data[0] > maxColl) ? maxColl : _data[0]; require(CTokenInterface(_addrData[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_addrData[0]); address borrowToken = getUnderlyingAddr(_addrData[1]); uint swapAmount = swap( [collAmount, _data[1], _data[2], _data[4]], // collAmount, minPrice, exchangeType, 0xPrice collToken, borrowToken, _addrData[2], _callData ); swapAmount -= getFee(swapAmount, user, _data[3], _addrData[1]); paybackDebt(swapAmount, _addrData[1], borrowToken, user); // handle 0x fee user.transfer(address(this).balance); CompoundLogger(COMPOUND_LOGGER).LogRepay(user, _data[0], swapAmount, collToken, borrowToken); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _data Amount and exchange data for the boost [amount, minPrice, exchangeType, gasCost, 0xPrice] /// @param _addrData Coll/Debt addresses [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _callData 0x calldata info function boost( uint[5] memory _data, // amount, minPrice, exchangeType, gasCost, 0xPrice address[3] memory _addrData, // cCollAddress, cBorrowAddress, exchangeAddress bytes memory _callData ) public payable { enterMarket(_addrData[0], _addrData[1]); address payable user = address(uint160(getUserAddress())); uint maxBorrow = getMaxBorrow(_addrData[1], address(this)); uint borrowAmount = (_data[0] > maxBorrow) ? maxBorrow : _data[0]; require(CTokenInterface(_addrData[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_addrData[0]); address borrowToken = getUnderlyingAddr(_addrData[1]); borrowAmount -= getFee(borrowAmount, user, _data[3], _addrData[1]); uint swapAmount = swap( [borrowAmount, _data[1], _data[2], _data[4]], // collAmount, minPrice, exchangeType, 0xPrice borrowToken, collToken, _addrData[2], _callData ); approveCToken(collToken, _addrData[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_addrData[0]).mint(swapAmount) == 0); } else { CEtherInterface(_addrData[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee user.transfer(address(this).balance); CompoundLogger(COMPOUND_LOGGER).LogBoost(user, _data[0], swapAmount, collToken, borrowToken); } }
@title Contract that implements repay/boost functionality
contract CompoundSaverProxy is CompoundSaverHelper, ExchangeHelper { function repay( bytes memory _callData ) public payable { enterMarket(_addrData[0], _addrData[1]); address payable user = address(uint160(getUserAddress())); uint maxColl = getMaxCollateral(_addrData[0], address(this)); uint collAmount = (_data[0] > maxColl) ? maxColl : _data[0]; require(CTokenInterface(_addrData[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_addrData[0]); address borrowToken = getUnderlyingAddr(_addrData[1]); uint swapAmount = swap( collToken, borrowToken, _addrData[2], _callData ); swapAmount -= getFee(swapAmount, user, _data[3], _addrData[1]); paybackDebt(swapAmount, _addrData[1], borrowToken, user); user.transfer(address(this).balance); CompoundLogger(COMPOUND_LOGGER).LogRepay(user, _data[0], swapAmount, collToken, borrowToken); } function boost( bytes memory _callData ) public payable { enterMarket(_addrData[0], _addrData[1]); address payable user = address(uint160(getUserAddress())); uint maxBorrow = getMaxBorrow(_addrData[1], address(this)); uint borrowAmount = (_data[0] > maxBorrow) ? maxBorrow : _data[0]; require(CTokenInterface(_addrData[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_addrData[0]); address borrowToken = getUnderlyingAddr(_addrData[1]); borrowAmount -= getFee(borrowAmount, user, _data[3], _addrData[1]); uint swapAmount = swap( borrowToken, collToken, _addrData[2], _callData ); approveCToken(collToken, _addrData[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_addrData[0]).mint(swapAmount) == 0); } CompoundLogger(COMPOUND_LOGGER).LogBoost(user, _data[0], swapAmount, collToken, borrowToken); } function boost( bytes memory _callData ) public payable { enterMarket(_addrData[0], _addrData[1]); address payable user = address(uint160(getUserAddress())); uint maxBorrow = getMaxBorrow(_addrData[1], address(this)); uint borrowAmount = (_data[0] > maxBorrow) ? maxBorrow : _data[0]; require(CTokenInterface(_addrData[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_addrData[0]); address borrowToken = getUnderlyingAddr(_addrData[1]); borrowAmount -= getFee(borrowAmount, user, _data[3], _addrData[1]); uint swapAmount = swap( borrowToken, collToken, _addrData[2], _callData ); approveCToken(collToken, _addrData[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_addrData[0]).mint(swapAmount) == 0); } CompoundLogger(COMPOUND_LOGGER).LogBoost(user, _data[0], swapAmount, collToken, borrowToken); } } else { user.transfer(address(this).balance); }
908,929
[ 1, 8924, 716, 4792, 2071, 528, 19, 25018, 14176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 21327, 55, 21851, 3886, 353, 21327, 55, 21851, 2276, 16, 18903, 2276, 288, 203, 203, 565, 445, 2071, 528, 12, 203, 3639, 1731, 3778, 389, 1991, 751, 203, 565, 262, 1071, 8843, 429, 288, 203, 3639, 6103, 3882, 278, 24899, 4793, 751, 63, 20, 6487, 389, 4793, 751, 63, 21, 19226, 203, 203, 3639, 1758, 8843, 429, 729, 273, 1758, 12, 11890, 16874, 12, 588, 1299, 1887, 1435, 10019, 203, 203, 3639, 2254, 943, 13535, 273, 7288, 13535, 2045, 287, 24899, 4793, 751, 63, 20, 6487, 1758, 12, 2211, 10019, 203, 203, 3639, 2254, 4508, 6275, 273, 261, 67, 892, 63, 20, 65, 405, 943, 13535, 13, 692, 943, 13535, 294, 389, 892, 63, 20, 15533, 203, 203, 3639, 2583, 12, 1268, 969, 1358, 24899, 4793, 751, 63, 20, 65, 2934, 266, 24903, 14655, 6291, 12, 12910, 6275, 13, 422, 374, 1769, 203, 203, 3639, 1758, 4508, 1345, 273, 10833, 765, 6291, 3178, 24899, 4793, 751, 63, 20, 19226, 203, 3639, 1758, 29759, 1345, 273, 10833, 765, 6291, 3178, 24899, 4793, 751, 63, 21, 19226, 203, 203, 3639, 2254, 7720, 6275, 273, 7720, 12, 203, 5411, 4508, 1345, 16, 203, 5411, 29759, 1345, 16, 203, 5411, 389, 4793, 751, 63, 22, 6487, 203, 5411, 389, 1991, 751, 203, 3639, 11272, 203, 203, 3639, 7720, 6275, 3947, 2812, 1340, 12, 22270, 6275, 16, 729, 16, 389, 892, 63, 23, 6487, 389, 4793, 751, 63, 21, 19226, 203, 203, 3639, 8843, 823, 758, 23602, 12, 22270, 6275, 16, 389, 4793, 751, 63, 21, 6487, 29759, 2 ]
pragma solidity ^0.5.0; /** @title Supply Chain. */ contract SupplyChain { address payable owner; bool public contractPaused = false; uint public skuCount; mapping (uint => Item ) public items; enum State { ForSale, Sold } struct Item { string name; uint sku; uint price; string image; State state; address payable seller; address payable buyer; } event ForSale(uint indexed sku); event Sold(uint indexed sku); /**@dev modifier used to only allow owner ***of the contract to call modfied function */ modifier isOwner () { require(msg.sender == owner); _;} /**@dev verifies that the buyer has payed enough Ether ***to complete the transaction */ modifier paidEnough(uint _price) { require(msg.value >= _price, "Not enough Ether."); _;} /**@dev checks whether there is a remaining ***balance to refund */ modifier checkValue(uint _sku) { _; uint _price = items[_sku].price; uint amountToRefund = msg.value - _price; items[_sku].buyer.transfer(amountToRefund); } /**@dev checks to see if the item requested has ***already been sold.*/ modifier forSale(uint _sku){ require(items[_sku].state == State.ForSale, "Item is not For Sale"); _; } /**@dev a circuit breaker to that prevents all ***app functionality if something bad occurs ***if the contract is paused, modified function stops*/ modifier checkIfPaused() { require(contractPaused == false); _; } /**@dev initializes the contract ***setting the owner of the contract to be msg.sender ***and initializing the id count of the items at 0 */ constructor() public { owner = msg.sender; skuCount = 0; } /**@dev adds an item to the contract storage. *@param _name Name of the item *@param _skuCount The identity number of the item *@param _image an image address of the item */ function addItem(string memory _name, uint _price, string memory _image) public checkIfPaused { emit ForSale(skuCount); items[skuCount] = Item({name: _name, sku:skuCount, price: _price, image: _image, state: State.ForSale, seller: msg.sender, buyer: address(0)}); skuCount = skuCount + 1; } /**@dev allows user to buy an item stored in the contract *@param sku the identity number of the item */ function buyItem(uint sku) public payable forSale(sku) paidEnough(msg.value) checkValue(sku) checkIfPaused { items[sku].buyer = msg.sender; items[sku].seller.transfer(items[sku].price); items[sku].state = State.Sold; emit Sold(sku); } /**@dev allows the owner of the contract to ***terminate execution of functions modified by ***a isPaused modifier */ function circuitBreaker() public isOwner { if(contractPaused == false) { contractPaused = true; } else { contractPaused = false; } } /**@dev returns the item with the specified sku *@param _sku the items identity number *@return name Name of the item *@return sku Id of the item *@return price Price of the item *@return state State of the Item (ForSale | Sold) *@return seller Seller of the Item *@return buyer Buyer of the item *@return image Image of the item */ function fetchItem(uint _sku) public view returns (string memory name, uint sku, uint price, uint state, address seller, address buyer, string memory image) { name = items[_sku].name; sku = items[_sku].sku; price = items[_sku].price; state = uint(items[_sku].state); seller = items[_sku].seller; buyer = items[_sku].buyer; image = items[_sku].image; return (name, sku, price, state, seller, buyer, image); } }
*@dev modifier used to only allow ownerof the contract to call modfied function /
modifier isOwner () { require(msg.sender == owner); _;}
12,961,918
[ 1, 20597, 1399, 358, 1338, 1699, 3410, 792, 326, 6835, 358, 745, 681, 74, 2092, 445, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 353, 5541, 1832, 288, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 389, 31, 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 ]
// SPDX-License-Identifier: MIT // File: @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/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/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/ExenoTokenIco.sol pragma solidity 0.8.4; contract ExenoTokenIco is Ownable, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; // Date when ICO starts uint256 public immutable startDate; // Token being sold IERC20 public immutable token; // Oracle for native currency market price AggregatorV3Interface public immutable priceFeed; // Source of tokens and destination for cash address payable public immutable wallet; // How much cash has been raised so far uint256 public cashRaised; // How many tokens have been sold so far uint256 public totalTokensPurchased; // Total number of unique beneficiaries uint256 public totalBeneficiaries; // Map of token purchases made by beneficiaries mapping(address => uint256) public tokenPurchases; // Map of cash payments made by beneficiaries mapping(address => uint256) public cashPayments; // How many US dollars an investor needs to pay for 10**4 tokens in the PreICO stage, e.g. 3500 means $0.35 uint256 public preIcoRate; // How many US dollars an investor needs to pay for 10**4 tokens in the ICO stage, e.g. 5000 means $0.50 uint256 public icoRate; // Minimum cumulative amount of tokens an investor is allowed to purchase uint256 public immutable minCap; // Maximum cumulative amount of tokens an investor is allowed to purchase uint256 public immutable maxCap; // Limit triggering automatic transition to the ICO stage uint256 public constant PRE_ICO_LIMIT = 50 * 1000 * 1000 ether; // Limit triggering automatic transition to the PostICO stage uint256 public constant TOTAL_ICO_LIMIT = 75 * 1000 * 1000 ether; // The current stage of the ICO process Stage public currentStage; // Posssible values for `currentStage` enum Stage { PreICO, ICO, PostICO } /** * Event for token purchase logging * @param purchaser Who paid for the tokens * @param beneficiary Who got the tokens * @param saleCode Associated sale code * @param cashAmount Cash paid for the purchase * @param tokenAmount Amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint16 indexed saleCode, uint256 cashAmount, uint256 tokenAmount ); /** * Event for stage change logging * @param previousStage Previous stage * @param currentStage Current stage */ event NextStage( Stage previousStage, Stage currentStage ); /** * Event for rates change logging * @param newPreIcoRate Previous stage * @param newIcoRate Current stage */ event UpdateRates( uint256 newPreIcoRate, uint256 newIcoRate ); /** * Event for cash forwarding logging * @param value Amount of cash transferred */ event ForwardCash( uint256 value ); modifier validAddress(address a) { require(a != address(0), "ExenoTokenIco: address cannot be zero"); require(a != address(this), "ExenoTokenIco: invalid address"); _; } constructor( IERC20 _token, AggregatorV3Interface _priceFeed, uint256 _preIcoRate, uint256 _icoRate, uint256 _minCap, uint256 _maxCap, address payable _wallet, uint256 _startDate ) validAddress(_wallet) { assert(PRE_ICO_LIMIT < TOTAL_ICO_LIMIT); require(_preIcoRate > 0, "ExenoTokenIco: _preIcoRate needs to be above zero"); require(_icoRate > _preIcoRate, "ExenoTokenIco: _icoRate needs to be above _preIcoRate"); require(_minCap > 0, "ExenoTokenIco: _minCap needs to be above zero"); require(_maxCap > _minCap, "ExenoTokenIco: _maxCap needs to be above _minCap"); require(_startDate >= block.timestamp, "ExenoTokenIco: _startDate should be a date in the future"); token = _token; priceFeed = _priceFeed; preIcoRate = _preIcoRate; icoRate = _icoRate; minCap = _minCap; maxCap = _maxCap; wallet = _wallet; startDate = _startDate; currentStage = Stage.PreICO; } /** * @notice Apply a new value for stage * @param newStage New stage */ function _setStage(Stage newStage) internal { emit NextStage(currentStage, newStage); currentStage = newStage; } /** * @notice Allows investors to purchase tokens * @param beneficiary For whom the token is purchased * @param saleCode Sale code associated with the purchase */ function _buyTokens(address beneficiary, uint16 saleCode) internal whenNotPaused nonReentrant { require(block.timestamp >= startDate, "ExenoTokenIco: sale has not started yet"); require(currentStage == Stage.PreICO || currentStage == Stage.ICO, "ExenoTokenIco: buying tokens is only allowed in preICO and ICO"); if (currentStage == Stage.PreICO) { assert(totalTokensPurchased < PRE_ICO_LIMIT); } else if (currentStage == Stage.ICO) { assert(totalTokensPurchased < TOTAL_ICO_LIMIT); } uint256 cashAmount = msg.value; require(cashAmount > 0, "ExenoTokenIco: invalid value"); (uint256 tokenAmount,) = convertFromCashAmount(cashAmount); require(token.balanceOf(wallet) >= tokenAmount, "ExenoTokenIco: not enough balance on the wallet account"); require(token.allowance(wallet, address(this)) >= tokenAmount, "ExenoTokenIco: not enough allowance from the wallet account"); uint256 existingPayment = cashPayments[beneficiary]; uint256 newPayment = existingPayment + cashAmount; uint256 existingPurchase = tokenPurchases[beneficiary]; uint256 newPurchase = existingPurchase + tokenAmount; require(newPurchase >= minCap, "ExenoTokenIco: purchase is below min cap"); require(newPurchase <= maxCap, "ExenoTokenIco: purchase is above max cap"); cashRaised += cashAmount; totalTokensPurchased += tokenAmount; cashPayments[beneficiary] = newPayment; tokenPurchases[beneficiary] = newPurchase; if (existingPurchase == 0) { totalBeneficiaries += 1; } token.safeTransferFrom(wallet, beneficiary, tokenAmount); emit TokenPurchase(msg.sender, beneficiary, saleCode, cashAmount, tokenAmount); if (currentStage == Stage.PreICO && totalTokensPurchased >= PRE_ICO_LIMIT) { _setStage(Stage.ICO); } else if (currentStage == Stage.ICO && totalTokensPurchased >= TOTAL_ICO_LIMIT) { _setStage(Stage.PostICO); } } /** * @notice Allows token purchasing via a simple transfer */ receive() external payable { _buyTokens(msg.sender, 0); } /** * @notice External access to `_buyTokens()` * @param beneficiary For whom the token is purchased * @param saleCode Sale code associated with the purchase */ function buyTokens(address beneficiary, uint16 saleCode) external payable validAddress(beneficiary) { _buyTokens(beneficiary, saleCode); } /** * @notice Allows owner to pause further token purchases */ function pause() external onlyOwner { _pause(); } /** * @notice Allows owner to unpause further token purchases */ function unpause() external onlyOwner { _unpause(); } /** * @notice Allows owner to update the stage */ function nextStage() external onlyOwner { require(currentStage == Stage.PreICO || currentStage == Stage.ICO, "ExenoTokenIco: changing stage is only allowed in preICO and ICO"); if (currentStage == Stage.PreICO) { _setStage(Stage.ICO); } else if (currentStage == Stage.ICO) { _setStage(Stage.PostICO); } } /** * @notice Allows owner to update the rates * @param newPreIcoRate New preICO rate * @param newIcoRate New ICO rate */ function updateRates(uint256 newPreIcoRate, uint256 newIcoRate) external onlyOwner { require(currentStage == Stage.PreICO || currentStage == Stage.ICO, "ExenoTokenIco: updating rates is only allowed in preICO and ICO"); require(newPreIcoRate > 0 && newPreIcoRate < newIcoRate, "ExenoTokenIco: preICO rate needs to be lower than ICO rate"); preIcoRate = newPreIcoRate; icoRate = newIcoRate; emit UpdateRates(newPreIcoRate, newIcoRate); } /** * @notice Allows owner to forward cash to the wallet */ function forwardCash() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "ExenoTokenIco: there no cash to forward"); Address.sendValue(wallet, balance); emit ForwardCash(balance); } /** * @notice Figures out the current rate based on the current stage * @return the current rate */ function currentRate() public view returns(uint256) { uint256 rate = 0; if (currentStage == Stage.PreICO) { rate = preIcoRate; } else if (currentStage == Stage.ICO) { rate = icoRate; } return rate; } /** * @notice Fetches the most recent market price of the native currency from an external oracle contract * @return price The most recent price and its decimals * @return decimals Decimals for the price */ function getLatestPrice() public view returns(uint256 price, uint8 decimals) { (, int256 answer, , ,) = priceFeed.latestRoundData(); price = uint256(answer); decimals = priceFeed.decimals(); } /** * @notice Shows the current amount of tokens available for sale * @return Owner's balance and this contract's allowance */ function checkAvailableFunds() external view returns(uint256, uint256) { return (token.balanceOf(wallet), token.allowance(wallet, address(this))); } /** * @notice Conversion calculation from cash amount (i.e. native currency) * @param cashAmount Amount of cash to be converted * @return tokenAmount Amount of tokens that can be purchased with the specified cashAmount * @return usdValue USD equivalent of cashAmount */ function convertFromCashAmount(uint256 cashAmount) public view returns(uint256 tokenAmount, uint256 usdValue) { (uint256 price, uint8 decimals) = getLatestPrice(); uint256 rate = currentRate(); tokenAmount = cashAmount * price * 10**4 / rate / 10**decimals; usdValue = cashAmount * price / 10**decimals; } /** * @notice Conversion calculation from token amount * @param tokenAmount Amount of tokens to be converted * @return cashAmount Amount of cash (i.e. native currency) needed to purchase the specified tokenAmount * @return usdValue USD equivalent of tokenAmount */ function convertFromTokenAmount(uint256 tokenAmount) external view returns(uint256 cashAmount, uint256 usdValue) { (uint256 price, uint8 decimals) = getLatestPrice(); uint256 rate = currentRate(); cashAmount = tokenAmount * 10**decimals * rate / price / 10**4; usdValue = tokenAmount * rate / 10**4; } /** * @notice Conversion calculation from USD value * @param usdValue Amount of USD to be converted * @return tokenAmount Amount of tokens that can be purchased with the specified usdValue * @return cashAmount Amount of cash (i.e. native currency) equivalent to the specified usdValue */ function convertFromUSDValue(uint256 usdValue) external view returns(uint256 tokenAmount, uint256 cashAmount) { (uint256 price, uint8 decimals) = getLatestPrice(); uint256 rate = currentRate(); tokenAmount = usdValue * 10**4 / rate; cashAmount = usdValue * 10**decimals / price; } }
* @notice Allows owner to pause further token purchases/
function pause() external onlyOwner { _pause(); }
12,115,743
[ 1, 19132, 3410, 358, 11722, 9271, 1147, 5405, 343, 3304, 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, 565, 445, 11722, 1435, 203, 3639, 3903, 1338, 5541, 203, 565, 288, 203, 3639, 389, 19476, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.13; import "./external/@openzeppelin/security/ReentrancyGuardUpgradeable.sol"; import "./external/spool-core/SpoolOwnable.sol"; import "./interfaces/ISpoolStaking.sol"; import "./external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "./external/@openzeppelin/utils/SafeCast.sol"; import "./interfaces/IVoSpoolRewards.sol"; import "./interfaces/IVoSPOOL.sol"; import "./interfaces/IRewardDistributor.sol"; /* ========== STRUCTS ========== */ // The reward configuration struct, containing all the necessary data of a typical Synthetix StakingReward contract struct RewardConfiguration { uint32 rewardsDuration; uint32 periodFinish; uint192 rewardRate; // rewards per second multiplied by accuracy uint32 lastUpdateTime; uint224 rewardPerTokenStored; mapping(address => uint256) userRewardPerTokenPaid; mapping(address => uint256) rewards; } /** * @notice Implementation of the {ISpoolStaking} interface. * * @dev * An adaptation of the Synthetix StakingRewards contract to support multiple tokens: * * https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol * * At stake, gradual voSPOOL (Spool DAO Voting Token) is minted and accumulated every week. * At unstake all voSPOOL is burned. The maturing process of voSPOOL restarts. */ contract SpoolStaking is ReentrancyGuardUpgradeable, SpoolOwnable, ISpoolStaking { using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ /// @notice Multiplier used when dealing reward calculations uint256 private constant REWARD_ACCURACY = 1e18; /* ========== STATE VARIABLES ========== */ /// @notice SPOOL token address IERC20 public immutable stakingToken; /// @notice voSPOOL token address IVoSPOOL public immutable voSpool; /// @notice voSPOOL token rewards address IVoSpoolRewards public immutable voSpoolRewards; /// @notice Spool reward distributor IRewardDistributor public immutable rewardDistributor; /// @notice Reward token configurations mapping(IERC20 => RewardConfiguration) public rewardConfiguration; /// @notice Reward tokens IERC20[] public rewardTokens; /// @notice Blacklisted force-removed tokens mapping(IERC20 => bool) public tokenBlacklist; /// @notice Total SPOOL staked uint256 public totalStaked; /// @notice Account SPOOL staked balance mapping(address => uint256) public balances; /// @notice Whitelist showing if address can stake for another address mapping(address => bool) public canStakeFor; /// @notice Mapping showing if and what address staked for another address /// @dev if address is 0, noone staked for address (or unstaking was permitted) mapping(address => address) public stakedBy; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the immutable values * * @param _stakingToken SPOOL token * @param _voSpool Spool voting token (voSPOOL) * @param _voSpoolRewards voSPOOL rewards contract * @param _rewardDistributor reward distributor contract * @param _spoolOwner Spool DAO owner contract */ constructor( IERC20 _stakingToken, IVoSPOOL _voSpool, IVoSpoolRewards _voSpoolRewards, IRewardDistributor _rewardDistributor, ISpoolOwner _spoolOwner ) SpoolOwnable(_spoolOwner) { stakingToken = _stakingToken; voSpool = _voSpool; voSpoolRewards = _voSpoolRewards; rewardDistributor = _rewardDistributor; } /* ========== INITIALIZER ========== */ function initialize() external initializer { __ReentrancyGuard_init(); } /* ========== VIEWS ========== */ function lastTimeRewardApplicable(IERC20 token) public view returns (uint32) { return uint32(_min(block.timestamp, rewardConfiguration[token].periodFinish)); } function rewardPerToken(IERC20 token) public view returns (uint224) { RewardConfiguration storage config = rewardConfiguration[token]; if (totalStaked == 0) return config.rewardPerTokenStored; uint256 timeDelta = lastTimeRewardApplicable(token) - config.lastUpdateTime; if (timeDelta == 0) return config.rewardPerTokenStored; return SafeCast.toUint224(config.rewardPerTokenStored + ((timeDelta * config.rewardRate) / totalStaked)); } function earned(IERC20 token, address account) public view returns (uint256) { RewardConfiguration storage config = rewardConfiguration[token]; uint256 accountStaked = balances[account]; if (accountStaked == 0) return config.rewards[account]; uint256 userRewardPerTokenPaid = config.userRewardPerTokenPaid[account]; return ((accountStaked * (rewardPerToken(token) - userRewardPerTokenPaid)) / REWARD_ACCURACY) + config.rewards[account]; } function rewardTokensCount() external view returns (uint256) { return rewardTokens.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant updateRewards(msg.sender) { _stake(msg.sender, amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function _stake(address account, uint256 amount) private { require(amount > 0, "SpoolStaking::_stake: Cannot stake 0"); unchecked { totalStaked = totalStaked += amount; balances[account] += amount; } // mint gradual voSPOOL for the account voSpool.mintGradual(account, amount); } function compound(bool doCompoundVoSpoolRewards) external nonReentrant { // collect SPOOL earned fom spool rewards and stake them uint256 reward = _getRewardForCompound(msg.sender, doCompoundVoSpoolRewards); if (reward > 0) { // update user rewards before staking _updateSpoolRewards(msg.sender); // update user voSPOOL based reward before staking // skip updating voSPOOL reward if we compounded form it as it's already updated if (!doCompoundVoSpoolRewards) { _updateVoSpoolReward(msg.sender); } // stake collected reward _stake(msg.sender, reward); // move compounded SPOOL reward to this contract rewardDistributor.payReward(address(this), stakingToken, reward); } } function unstake(uint256 amount) public nonReentrant notStakedBy updateRewards(msg.sender) { require(amount > 0, "SpoolStaking::unstake: Cannot withdraw 0"); require(amount <= balances[msg.sender], "SpoolStaking::unstake: Cannot unstake more than staked"); unchecked { totalStaked = totalStaked -= amount; balances[msg.sender] -= amount; } stakingToken.safeTransfer(msg.sender, amount); // burn gradual voSPOOL for the sender if (balances[msg.sender] == 0) { voSpool.burnGradual(msg.sender, 0, true); } else { voSpool.burnGradual(msg.sender, amount, false); } emit Unstaked(msg.sender, amount); } function _getRewardForCompound(address account, bool doCompoundVoSpoolRewards) internal updateReward(stakingToken, account) returns (uint256 reward) { RewardConfiguration storage config = rewardConfiguration[stakingToken]; reward = config.rewards[account]; if (reward > 0) { config.rewards[account] = 0; emit RewardCompounded(msg.sender, reward); } if (doCompoundVoSpoolRewards) { _updateVoSpoolReward(account); uint256 voSpoolreward = voSpoolRewards.flushRewards(account); if (voSpoolreward > 0) { reward += voSpoolreward; emit VoRewardCompounded(msg.sender, reward); } } } function getRewards(IERC20[] memory tokens, bool doClaimVoSpoolRewards) external nonReentrant notStakedBy { for (uint256 i; i < tokens.length; i++) { _getReward(tokens[i], msg.sender); } if (doClaimVoSpoolRewards) { _getVoSpoolRewards(msg.sender); } } function getActiveRewards(bool doClaimVoSpoolRewards) external nonReentrant notStakedBy { _getActiveRewards(msg.sender); if (doClaimVoSpoolRewards) { _getVoSpoolRewards(msg.sender); } } function getUpdatedVoSpoolRewardAmount() external returns (uint256 rewards) { // update rewards rewards = voSpoolRewards.updateRewards(msg.sender); // update and store users voSPOOL voSpool.updateUserVotingPower(msg.sender); } function _getActiveRewards(address account) internal { uint256 _rewardTokensCount = rewardTokens.length; for (uint256 i; i < _rewardTokensCount; i++) { _getReward(rewardTokens[i], account); } } function _getReward(IERC20 token, address account) internal updateReward(token, account) { RewardConfiguration storage config = rewardConfiguration[token]; require(config.rewardsDuration != 0, "SpoolStaking::_getReward: Bad reward token"); uint256 reward = config.rewards[account]; if (reward > 0) { config.rewards[account] = 0; rewardDistributor.payReward(account, token, reward); emit RewardPaid(token, account, reward); } } function _getVoSpoolRewards(address account) internal { _updateVoSpoolReward(account); uint256 reward = voSpoolRewards.flushRewards(account); if (reward > 0) { rewardDistributor.payReward(account, stakingToken, reward); emit VoSpoolRewardPaid(stakingToken, account, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ function stakeFor(address account, uint256 amount) external nonReentrant canStakeForAddress(account) updateRewards(account) { _stake(account, amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); stakedBy[account] = msg.sender; emit StakedFor(account, msg.sender, amount); } /** * @notice Allow unstake for `allowFor` address * @dev * * Requirements: * * - the caller must be the Spool DAO or address that staked for `allowFor` address * * @param allowFor address to allow unstaking for */ function allowUnstakeFor(address allowFor) external { require( (canStakeFor[msg.sender] && stakedBy[allowFor] == msg.sender) || isSpoolOwner(), "SpoolStaking::allowUnstakeFor: Cannot allow unstaking for address" ); // reset address to 0 to allow unstaking stakedBy[allowFor] = address(0); } /** * @notice Allows a new token to be added to the reward system * * @dev * Emits an {TokenAdded} event indicating the newly added reward token * and configuration * * Requirements: * * - the caller must be the reward Spool DAO * - the reward duration must be non-zero * - the token must not have already been added * */ function addToken( IERC20 token, uint32 rewardsDuration, uint256 reward ) external onlyOwner { RewardConfiguration storage config = rewardConfiguration[token]; require(!tokenBlacklist[token], "SpoolStaking::addToken: Cannot add blacklisted token"); require(rewardsDuration != 0, "SpoolStaking::addToken: Reward duration cannot be 0"); require(config.lastUpdateTime == 0, "SpoolStaking::addToken: Token already added"); rewardTokens.push(token); config.rewardsDuration = rewardsDuration; if (reward > 0) { _notifyRewardAmount(token, reward); } } function notifyRewardAmount( IERC20 token, uint32 _rewardsDuration, uint256 reward ) external onlyOwner { RewardConfiguration storage config = rewardConfiguration[token]; config.rewardsDuration = _rewardsDuration; require( rewardConfiguration[token].lastUpdateTime != 0, "SpoolStaking::notifyRewardAmount: Token not yet added" ); _notifyRewardAmount(token, reward); } function _notifyRewardAmount(IERC20 token, uint256 reward) private updateReward(token, address(0)) { RewardConfiguration storage config = rewardConfiguration[token]; require( config.rewardPerTokenStored + (reward * REWARD_ACCURACY) <= type(uint192).max, "SpoolStaking::_notifyRewardAmount: Reward amount too big" ); uint32 newPeriodFinish = uint32(block.timestamp) + config.rewardsDuration; if (block.timestamp >= config.periodFinish) { config.rewardRate = SafeCast.toUint192((reward * REWARD_ACCURACY) / config.rewardsDuration); emit RewardAdded(token, reward, config.rewardsDuration); } else { uint256 remaining = config.periodFinish - block.timestamp; uint256 leftover = remaining * config.rewardRate; uint192 newRewardRate = SafeCast.toUint192((reward * REWARD_ACCURACY + leftover) / config.rewardsDuration); config.rewardRate = newRewardRate; emit RewardUpdated(token, reward, leftover, config.rewardsDuration, newPeriodFinish); } config.lastUpdateTime = uint32(block.timestamp); config.periodFinish = newPeriodFinish; } // End rewards emission earlier function updatePeriodFinish(IERC20 token, uint32 timestamp) external onlyOwner updateReward(token, address(0)) { if (rewardConfiguration[token].lastUpdateTime > timestamp) { rewardConfiguration[token].periodFinish = rewardConfiguration[token].lastUpdateTime; } else { rewardConfiguration[token].periodFinish = timestamp; } emit PeriodFinishUpdated(token, rewardConfiguration[token].periodFinish); } /** * @notice Remove reward from vault rewards configuration. * @dev * Used to sanitize vault and save on gas, after the reward has ended. * Users will be able to claim rewards * * Requirements: * * - the caller must be the spool owner or Spool DAO * - cannot claim vault underlying token * - cannot only execute if the reward finished * * @param token Token address to remove */ function removeReward(IERC20 token) external onlyOwner onlyFinished(token) updateReward(token, address(0)) { _removeReward(token); } /** * @notice Allow an address to stake for another address. * @dev * Requirements: * * - the caller must be the distributor * * @param account Address to allow * @param _canStakeFor True to allow, false to remove allowance */ function setCanStakeFor(address account, bool _canStakeFor) external onlyOwner { canStakeFor[account] = _canStakeFor; emit CanStakeForSet(account, _canStakeFor); } function recoverERC20( IERC20 tokenAddress, uint256 tokenAmount, address recoverTo ) external onlyOwner { require(tokenAddress != stakingToken, "SpoolStaking::recoverERC20: Cannot withdraw the staking token"); tokenAddress.safeTransfer(recoverTo, tokenAmount); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @notice Syncs rewards across all tokens of the system * * This function is meant to be invoked every time the instant deposit * of a user changes. */ function _updateRewards(address account) private { // update SPOOL based rewards _updateSpoolRewards(account); // update voSPOOL based reward _updateVoSpoolReward(account); } function _updateSpoolRewards(address account) private { uint256 _rewardTokensCount = rewardTokens.length; // update SPOOL based rewards for (uint256 i; i < _rewardTokensCount; i++) _updateReward(rewardTokens[i], account); } function _updateReward(IERC20 token, address account) private { RewardConfiguration storage config = rewardConfiguration[token]; config.rewardPerTokenStored = rewardPerToken(token); config.lastUpdateTime = lastTimeRewardApplicable(token); if (account != address(0)) { config.rewards[account] = earned(token, account); config.userRewardPerTokenPaid[account] = config.rewardPerTokenStored; } } /** * @notice Update rewards collected from account voSPOOL * @dev * First we update rewards calling `voSpoolRewards.updateRewards` * - Here we only simulate the reward accumulated over tranches * Then we update and store users power by calling voSPOOL contract * - Here we actually store the udated values. * - If store wouldn't happen, next time we'd simulate the same voSPOOL tranches again */ function _updateVoSpoolReward(address account) private { // update rewards voSpoolRewards.updateRewards(account); // update and store users voSPOOL voSpool.updateUserVotingPower(account); } function _removeReward(IERC20 token) private { uint256 _rewardTokensCount = rewardTokens.length; for (uint256 i; i < _rewardTokensCount; i++) { if (rewardTokens[i] == token) { rewardTokens[i] = rewardTokens[_rewardTokensCount - 1]; rewardTokens.pop(); emit RewardRemoved(token); break; } } } function _onlyFinished(IERC20 token) private view { require( block.timestamp > rewardConfiguration[token].periodFinish, "SpoolStaking::_onlyFinished: Reward not finished" ); } function _min(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? b : a; } /* ========== MODIFIERS ========== */ modifier updateReward(IERC20 token, address account) { _updateReward(token, account); _; } modifier updateRewards(address account) { _updateRewards(account); _; } modifier canStakeForAddress(address account) { // verify sender can stake for require( canStakeFor[msg.sender] || isSpoolOwner(), "SpoolStaking::canStakeForAddress: Cannot stake for other addresses" ); // if address already staked, verify further if (balances[account] > 0) { // verify address was staked by some other address require(stakedBy[account] != address(0), "SpoolStaking::canStakeForAddress: Address already staked"); // verify address was staked by the sender or sender is the Spool DAO require( stakedBy[account] == msg.sender || isSpoolOwner(), "SpoolStaking::canStakeForAddress: Address staked by another address" ); } _; } modifier notStakedBy() { require(stakedBy[msg.sender] == address(0), "SpoolStaking::notStakedBy: Cannot withdraw until allowed"); _; } modifier onlyFinished(IERC20 token) { _onlyFinished(token); _; } } // 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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 pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./interfaces/ISpoolOwner.sol"; abstract contract SpoolOwnable { ISpoolOwner internal immutable spoolOwner; constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } function _onlyOwner() internal view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IRewardDistributor { /* ========== FUNCTIONS ========== */ function payRewards( address account, IERC20[] memory tokens, uint256[] memory amounts ) external; function payReward( address account, IERC20 token, uint256 amount ) external; /* ========== EVENTS ========== */ event RewardPaid(IERC20 token, address indexed account, uint256 amount); event RewardRetrieved(IERC20 token, address indexed account, uint256 amount); event DistributorUpdated(address indexed user, bool set); event PauserUpdated(address indexed user, bool set); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; interface ISpoolStaking { /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); event StakedFor(address indexed stakedFor, address indexed stakedBy, uint256 amount); event Unstaked(address indexed user, uint256 amount); event RewardCompounded(address indexed user, uint256 reward); event VoRewardCompounded(address indexed user, uint256 reward); event RewardPaid(IERC20 token, address indexed user, uint256 reward); event VoSpoolRewardPaid(IERC20 token, address indexed user, uint256 reward); event RewardAdded(IERC20 indexed token, uint256 amount, uint256 duration); event RewardUpdated(IERC20 indexed token, uint256 amount, uint256 leftover, uint256 duration, uint32 periodFinish); event RewardRemoved(IERC20 indexed token); event PeriodFinishUpdated(IERC20 indexed token, uint32 periodFinish); event CanStakeForSet(address indexed account, bool canStakeFor); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; /* ========== STRUCTS ========== */ /** * @notice global gradual struct * @member totalMaturedVotingPower total fully-matured voting power amount * @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount) * @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power) * @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated */ struct GlobalGradual { uint48 totalMaturedVotingPower; uint48 totalMaturingAmount; uint56 totalRawUnmaturedVotingPower; uint16 lastUpdatedTrancheIndex; } /** * @notice user tranche position struct, pointing at user tranche * @dev points at `userTranches` mapping * @member arrayIndex points at `userTranches` * @member position points at UserTranches position from zero to three (zero, one, two, or three) */ struct UserTranchePosition { uint16 arrayIndex; uint8 position; } /** * @notice user gradual struct, similar to global gradual holds user gragual voting power values * @dev points at `userTranches` mapping * @member maturedVotingPower users fully-matured voting power amount * @member maturingAmount users maturing amount * @member rawUnmaturedVotingPower users raw voting power still maturing every tranche * @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche * @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche * @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated */ struct UserGradual { uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore uint48 maturingAmount; // total maturing amount (also maximum matured) uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty) UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position uint16 lastUpdatedTrancheIndex; } /** * @title Spool DAO Voting Token interface */ interface IVoSPOOL { /* ========== FUNCTIONS ========== */ function mint(address, uint256) external; function burn(address, uint256) external; function mintGradual(address, uint256) external; function burnGradual( address, uint256, bool ) external; function updateVotingPower() external; function updateUserVotingPower(address user) external; function getTotalGradualVotingPower() external returns (uint256); function getUserGradualVotingPower(address user) external returns (uint256); function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory); function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory); function getCurrentTrancheIndex() external view returns (uint16); function getLastFinishedTrancheIndex() external view returns (uint16); /* ========== EVENTS ========== */ event Minted(address indexed recipient, uint256 amount); event Burned(address indexed source, uint256 amount); event GradualMinted(address indexed recipient, uint256 amount); event GradualBurned(address indexed source, uint256 amount, bool burnAll); event GlobalGradualUpdated( uint16 indexed lastUpdatedTrancheIndex, uint48 totalMaturedVotingPower, uint48 totalMaturingAmount, uint56 totalRawUnmaturedVotingPower ); event UserGradualUpdated( address indexed user, uint16 indexed lastUpdatedTrancheIndex, uint48 maturedVotingPower, uint48 maturingAmount, uint56 rawUnmaturedVotingPower ); event MinterSet(address indexed minter, bool set); event GradualMinterSet(address indexed minter, bool set); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface IVoSpoolRewards { /* ========== FUNCTIONS ========== */ function updateRewards(address user) external returns (uint256); function flushRewards(address user) external returns (uint256); /* ========== EVENTS ========== */ event RewardRateUpdated(uint8 indexed fromTranche, uint8 indexed toTranche, uint112 rewardPerTranche); event RewardEnded( uint256 indexed rewardRatesIndex, uint8 indexed fromTranche, uint8 indexed toTranche, uint8 currentTrancheIndex ); event UserRewardUpdated(address indexed user, uint8 lastRewardRateIndex, uint248 earned); }
* @notice Allow an address to stake for another address. @dev Requirements: - the caller must be the distributor @param account Address to allow @param _canStakeFor True to allow, false to remove allowance/
function setCanStakeFor(address account, bool _canStakeFor) external onlyOwner { canStakeFor[account] = _canStakeFor; emit CanStakeForSet(account, _canStakeFor); }
1,407,122
[ 1, 7009, 392, 1758, 358, 384, 911, 364, 4042, 1758, 18, 225, 29076, 30, 300, 326, 4894, 1297, 506, 326, 1015, 19293, 225, 2236, 5267, 358, 1699, 225, 389, 4169, 510, 911, 1290, 1053, 358, 1699, 16, 629, 358, 1206, 1699, 1359, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 444, 2568, 510, 911, 1290, 12, 2867, 2236, 16, 1426, 389, 4169, 510, 911, 1290, 13, 3903, 1338, 5541, 288, 203, 202, 202, 4169, 510, 911, 1290, 63, 4631, 65, 273, 389, 4169, 510, 911, 1290, 31, 203, 202, 202, 18356, 4480, 510, 911, 1290, 694, 12, 4631, 16, 389, 4169, 510, 911, 1290, 1769, 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 ]
contract Consulting { /* * This contract accepts payment from clients, and payout to engineer and manager. */ address public engineer; address public manager; uint public createdTime; uint public updatedTime; function Consulting(address _engineer, address _manager) { engineer = 0x2207bD0174840f4C728c0B07DE9bDD643Ee2E7d6; manager = 0xddd31eb39d56d51b50172884bd2b88e1f6264f95; createdTime = block.timestamp; updatedTime = block.timestamp; } /* Contract payout hald */ function payout() returns (bool _success) { if(msg.sender == engineer || msg.sender == manager) { engineer.send(this.balance / 2); manager.send(this.balance); updatedTime = block.timestamp; _success = true; }else{ _success = false; } } }
Contract payout hald */
function payout() returns (bool _success) { if(msg.sender == engineer || msg.sender == manager) { engineer.send(this.balance / 2); manager.send(this.balance); updatedTime = block.timestamp; _success = true; _success = false; } }
15,792,371
[ 1, 8924, 293, 2012, 19514, 72, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 293, 2012, 1435, 1135, 261, 6430, 389, 4768, 13, 288, 203, 3639, 309, 12, 3576, 18, 15330, 422, 4073, 264, 747, 1234, 18, 15330, 422, 3301, 13, 288, 203, 2398, 4073, 264, 18, 4661, 12, 2211, 18, 12296, 342, 576, 1769, 203, 2398, 3301, 18, 4661, 12, 2211, 18, 12296, 1769, 203, 2398, 3526, 950, 273, 1203, 18, 5508, 31, 203, 2398, 389, 4768, 273, 638, 31, 203, 5411, 389, 4768, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // 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/>. library BConst { uint public constant BONE = 10**18; uint public constant MIN_BOUND_TOKENS = 2; uint public constant MAX_BOUND_TOKENS = 8; uint public constant DEFAULT_FEE = BONE * 3 / 1000; // 0.3% uint public constant MIN_FEE = BONE / 10**6; uint public constant MAX_FEE = BONE / 10; uint public constant DEFAULT_COLLECTED_FEE = BONE / 2000; // 0.05% uint public constant MAX_COLLECTED_FEE = BONE / 200; // 0.5% uint public constant DEFAULT_EXIT_FEE = 0; uint public constant MAX_EXIT_FEE = BONE / 1000; // 0.1% uint public constant MIN_WEIGHT = BONE; uint public constant MAX_WEIGHT = BONE * 50; uint public constant MAX_TOTAL_WEIGHT = BONE * 50; uint public constant MIN_BALANCE = BONE / 10**12; uint public constant DEFAULT_INIT_POOL_SUPPLY = BONE * 100; uint public constant MIN_INIT_POOL_SUPPLY = BONE / 1000; uint public constant MAX_INIT_POOL_SUPPLY = BONE * 10**18; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint public constant BPOW_PRECISION = BONE / 10**10; uint public constant MAX_IN_RATIO = BONE / 2; uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract BNum { function btoi(uint a) internal pure returns (uint) { return a / BConst.BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BConst.BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add overflow"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "sub underflow"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "mul overflow"); uint c1 = c0 + (BConst.BONE / 2); require(c1 >= c0, "mul overflow"); uint c2 = c1 / BConst.BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "div by 0"); uint c0 = a * BConst.BONE; require(a == 0 || c0 / a == BConst.BONE, "div internal"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "div internal"); // badd require uint c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BConst.BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= BConst.MIN_BPOW_BASE, "base too low"); require(base <= BConst.MAX_BPOW_BASE, "base too high"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BConst.BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BConst.BONE); uint term = BConst.BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BConst.BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BConst.BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } // 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/>. // Highly opinionated token implementation interface IERC20 { event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); } contract BTokenBase is BNum { mapping(address => uint) internal _balance; mapping(address => mapping(address=>uint)) internal _allowance; uint internal _totalSupply; event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function _mint(uint amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint amt) internal { require(_balance[address(this)] >= amt, "!bal"); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move(address src, address dst, uint amt) internal { require(_balance[src] >= amt, "!bal"); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint amt) internal { _move(address(this), to, amt); } function _pull(address from, uint amt) internal { _move(from, address(this), amt); } } contract BToken is BTokenBase, IERC20 { string private _name = "Value Liquidity Provider"; string private _symbol = "VLP"; uint8 private _decimals = 18; 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 allowance(address src, address dst) external override view returns (uint) { return _allowance[src][dst]; } function balanceOf(address whom) external override view returns (uint) { return _balance[whom]; } function totalSupply() public override view returns (uint) { return _totalSupply; } function approve(address dst, uint amt) external override returns (bool) { _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint amt) external returns (bool) { _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint amt) external returns (bool) { uint oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint amt) external override returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom(address src, address dst, uint amt) external override returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender], "!spender"); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(msg.sender, dst, _allowance[src][msg.sender]); } return true; } } // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. contract BMath is BNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee (+ collectedFee) // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) public pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BConst.BONE, bsub(BConst.BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee (+ collectedFee) // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BConst.BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BConst.BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee (+ collectedFee) // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BConst.BONE); tokenAmountIn = bsub(BConst.BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee (+ collectedFee)\ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure returns (uint poolAmountOut) { // @dev Charge the trading fee for the proportion of tokenAi // which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BConst.BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BConst.BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee (+ collectedFee) \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BConst.BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BConst.BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BConst.BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee (+ collectedFee) * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee, uint exitFee ) public pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BConst.BONE, exitFee)); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BConst.BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BConst.BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BConst.BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee (+ collectedFee) ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee, uint exitFee ) public pure returns (uint poolAmountIn) { // charge swap fee on the output token side uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint zoo = bsub(BConst.BONE, normalizedWeight); uint zar = bmul(zoo, swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BConst.BONE, zar)); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BConst.BONE, exitFee)); return poolAmountIn; } } // 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/>. interface IBFactory { function collectedToken() external view returns(address); } contract BPool is BToken, BMath { struct Record { bool bound; // is token bound to pool uint index; // private uint denorm; // denormalized weight uint balance; } event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_CALL( bytes4 indexed sig, address indexed caller, bytes data ) anonymous; modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } event LOG_COLLECTED_FUND( address indexed collectedToken, uint256 collectedAmount ); modifier _lock_() { require(!_mutex, "reentry"); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex, "reentry"); _; } bool private _mutex; uint public version = 1001; address public factory; // BFactory address to push token exitFee to address public controller; // has CONTROL role bool public publicSwap; // `setSwapFee` and `finalize` require CONTROL // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` uint public initPoolSupply; uint public swapFee; uint public collectedFee; // 0.05% | https://yfv.finance/vip-vote/vip_5 uint public exitFee; bool public finalized; address[] private _tokens; mapping(address => Record) private _records; uint private _totalWeight; constructor(address _factory) public { controller = _factory; factory = _factory; initPoolSupply = BConst.DEFAULT_INIT_POOL_SUPPLY; swapFee = BConst.DEFAULT_FEE; collectedFee = BConst.DEFAULT_COLLECTED_FEE; exitFee = BConst.DEFAULT_EXIT_FEE; publicSwap = false; finalized = false; } function setInitPoolSupply(uint _initPoolSupply) public _logs_ { require(!finalized, "finalized"); require(msg.sender == controller, "!controller"); require(_initPoolSupply >= BConst.MIN_INIT_POOL_SUPPLY, "<minInitPoolSup"); require(_initPoolSupply <= BConst.MAX_INIT_POOL_SUPPLY, ">maxInitPoolSup"); initPoolSupply = _initPoolSupply; } function setCollectedFee(uint _collectedFee) public _logs_ { require(msg.sender == factory, "!factory"); require(_collectedFee <= BConst.MAX_COLLECTED_FEE, ">maxCoFee"); require(bmul(_collectedFee, 2) <= swapFee, ">swapFee/2"); collectedFee = _collectedFee; } function setExitFee(uint _exitFee) public _logs_ { require(!finalized, "finalized"); require(msg.sender == factory, "!factory"); require(_exitFee <= BConst.MAX_EXIT_FEE, ">maxExitFee"); exitFee = _exitFee; } function isBound(address t) external view returns (bool) { return _records[t].bound; } function getNumTokens() external view returns (uint) { return _tokens.length; } function getCurrentTokens() external view _viewlock_ returns (address[] memory tokens) { return _tokens; } function getFinalTokens() external view _viewlock_ returns (address[] memory tokens) { require(finalized, "!finalized"); return _tokens; } function getDenormalizedWeight(address token) external view _viewlock_ returns (uint) { require(_records[token].bound, "!bound"); return _records[token].denorm; } function getTotalDenormalizedWeight() external view _viewlock_ returns (uint) { return _totalWeight; } function getNormalizedWeight(address token) external view _viewlock_ returns (uint) { require(_records[token].bound, "!bound"); uint denorm = _records[token].denorm; return bdiv(denorm, _totalWeight); } function getBalance(address token) external view _viewlock_ returns (uint) { require(_records[token].bound, "!bound"); return _records[token].balance; } function setSwapFee(uint _swapFee) external _lock_ _logs_ { require(!finalized, "finalized"); require(msg.sender == controller, "!controller"); require(_swapFee >= BConst.MIN_FEE, "<minFee"); require(_swapFee <= BConst.MAX_FEE, ">maxFee"); require(bmul(collectedFee, 2) <= _swapFee, "<collectedFee*2"); swapFee = _swapFee; } function setController(address _controller) external _lock_ _logs_ { require(msg.sender == controller, "!controller"); controller = _controller; } function setPublicSwap(bool _publicSwap) external _lock_ _logs_ { require(!finalized, "finalized"); require(msg.sender == controller, "!controller"); publicSwap = _publicSwap; } function finalize() external _lock_ _logs_ { require(msg.sender == controller, "!controller"); require(!finalized, "finalized"); require(_tokens.length >= BConst.MIN_BOUND_TOKENS, "<minTokens"); finalized = true; publicSwap = true; _mintPoolShare(initPoolSupply); _pushPoolShare(msg.sender, initPoolSupply); } function bind(address token, uint balance, uint denorm) external _logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does { require(msg.sender == controller, "!controller"); require(!_records[token].bound, "bound"); require(!finalized, "finalized"); require(_tokens.length < BConst.MAX_BOUND_TOKENS, ">maxTokens"); _records[token] = Record({ bound: true, index: _tokens.length, denorm: 0, // balance and denorm will be validated balance: 0 // and set by `rebind` }); _tokens.push(token); rebind(token, balance, denorm); } function rebind(address token, uint balance, uint denorm) public _lock_ _logs_ { require(msg.sender == controller, "!controller"); require(_records[token].bound, "!bound"); require(!finalized, "finalized"); require(denorm >= BConst.MIN_WEIGHT, "<minWeight"); require(denorm <= BConst.MAX_WEIGHT, ">maxWeight"); require(balance >= BConst.MIN_BALANCE, "<minBal"); // Adjust the denorm and totalWeight uint oldWeight = _records[token].denorm; if (denorm > oldWeight) { _totalWeight = badd(_totalWeight, bsub(denorm, oldWeight)); require(_totalWeight <= BConst.MAX_TOTAL_WEIGHT, ">maxTWeight"); } else if (denorm < oldWeight) { _totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm)); } _records[token].denorm = denorm; // Adjust the balance record and actual token balance uint oldBalance = _records[token].balance; _records[token].balance = balance; if (balance > oldBalance) { _pullUnderlying(token, msg.sender, bsub(balance, oldBalance)); } else if (balance < oldBalance) { // In this case liquidity is being withdrawn, so charge EXIT_FEE uint tokenBalanceWithdrawn = bsub(oldBalance, balance); uint tokenExitFee = bmul(tokenBalanceWithdrawn, exitFee); _pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee)); _pushUnderlying(token, factory, tokenExitFee); } } function unbind(address token) external _lock_ _logs_ { require(msg.sender == controller, "!controller"); require(_records[token].bound, "!bound"); require(!finalized, "finalized"); uint tokenBalance = _records[token].balance; uint tokenExitFee = bmul(tokenBalance, exitFee); _totalWeight = bsub(_totalWeight, _records[token].denorm); // Swap the token-to-unbind with the last token, // then delete the last token uint index = _records[token].index; uint last = _tokens.length - 1; _tokens[index] = _tokens[last]; _records[_tokens[index]].index = index; _tokens.pop(); _records[token] = Record({ bound: false, index: 0, denorm: 0, balance: 0 }); _pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee)); _pushUnderlying(token, factory, tokenExitFee); } // Absorb any tokens that have been sent to this contract into the pool function gulp(address token) external _logs_ _lock_ { require(_records[token].bound, "!bound"); _records[token].balance = IERC20(token).balanceOf(address(this)); } function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound, "!bound"); require(_records[tokenOut].bound, "!bound"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, swapFee); } function getSpotPriceSansFee(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound, "!bound"); require(_records[tokenOut].bound, "!bound"); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0); } function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external _lock_ _logs_ { require(finalized, "!finalized"); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "errMathAprox"); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountIn = bmul(ratio, bal); require(tokenAmountIn != 0, "errMathAprox"); require(tokenAmountIn <= maxAmountsIn[i], "<limIn"); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external _lock_ _logs_ { require(finalized, "!finalized"); uint poolTotal = totalSupply(); uint _exitFee = bmul(poolAmountIn, exitFee); uint pAiAfterExitFee = bsub(poolAmountIn, _exitFee); uint ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "errMathAprox"); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(factory, _exitFee); _burnPoolShare(pAiAfterExitFee); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountOut = bmul(ratio, bal); require(tokenAmountOut != 0, "errMathAprox"); require(tokenAmountOut >= minAmountsOut[i], "<limO"); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } } function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external _lock_ _logs_ returns (uint tokenAmountOut, uint spotPriceAfter) { require(_records[tokenIn].bound, "!bound"); require(_records[tokenOut].bound, "!bound"); require(publicSwap, "!publicSwap"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, BConst.MAX_IN_RATIO), ">maxIRat"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, swapFee ); require(spotPriceBefore <= maxPrice, "badLimPrice"); tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, swapFee ); require(tokenAmountOut >= minAmountOut, "<limO"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, swapFee ); require(spotPriceAfter >= spotPriceBefore, "errMathAprox"); require(spotPriceAfter <= maxPrice, ">limPrice"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "errMathAprox"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); uint _subTokenAmountIn; (_subTokenAmountIn, tokenAmountOut) = _pushCollectedFundGivenOut(tokenIn, tokenAmountIn, tokenOut, tokenAmountOut); if (_subTokenAmountIn > 0) inRecord.balance = bsub(inRecord.balance, _subTokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external _lock_ _logs_ returns (uint tokenAmountIn, uint spotPriceAfter) { require(_records[tokenIn].bound, "!bound"); require(_records[tokenOut].bound, "!bound"); require(publicSwap, "!publicSwap"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, BConst.MAX_OUT_RATIO), ">maxORat"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, swapFee ); require(spotPriceBefore <= maxPrice, "badLimPrice"); tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, swapFee ); require(tokenAmountIn <= maxAmountIn, "<limIn"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, swapFee ); require(spotPriceAfter >= spotPriceBefore, "errMathAprox"); require(spotPriceAfter <= maxPrice, ">limPrice"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "errMathAprox"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); uint _collectedFeeAmount = _pushCollectedFundGivenIn(tokenIn, tokenAmountIn); if (_collectedFeeAmount > 0) inRecord.balance = bsub(inRecord.balance, _collectedFeeAmount); return (tokenAmountIn, spotPriceAfter); } function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut) external _lock_ _logs_ returns (uint poolAmountOut) { require(finalized, "!finalized"); require(_records[tokenIn].bound, "!bound"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, BConst.MAX_IN_RATIO), ">maxIRat"); Record storage inRecord = _records[tokenIn]; poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, swapFee ); require(poolAmountOut >= minPoolAmountOut, "<limO"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); uint _subTokenAmountIn; (_subTokenAmountIn, poolAmountOut) = _pushCollectedFundGivenOut(tokenIn, tokenAmountIn, address(this), poolAmountOut); if (_subTokenAmountIn > 0) inRecord.balance = bsub(inRecord.balance, _subTokenAmountIn); _pushPoolShare(msg.sender, poolAmountOut); return poolAmountOut; } function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn) external _lock_ _logs_ returns (uint tokenAmountIn) { require(finalized, "!finalized"); require(_records[tokenIn].bound, "!bound"); Record storage inRecord = _records[tokenIn]; tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, swapFee ); require(tokenAmountIn != 0, "errMathAprox"); require(tokenAmountIn <= maxAmountIn, "<limIn"); require(tokenAmountIn <= bmul(_records[tokenIn].balance, BConst.MAX_IN_RATIO), ">maxIRat"); inRecord.balance = badd(inRecord.balance, tokenAmountIn); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); uint _collectedFeeAmount = _pushCollectedFundGivenIn(tokenIn, tokenAmountIn); if (_collectedFeeAmount > 0) inRecord.balance = bsub(inRecord.balance, _collectedFeeAmount); return tokenAmountIn; } function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut) external _lock_ _logs_ returns (uint tokenAmountOut) { require(finalized, "!finalized"); require(_records[tokenOut].bound, "!bound"); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, swapFee, exitFee ); require(tokenAmountOut >= minAmountOut, "<limO"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, BConst.MAX_OUT_RATIO), ">maxORat"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); uint _exitFee = bmul(poolAmountIn, exitFee); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, _exitFee)); _pushPoolShare(factory, _exitFee); (, tokenAmountOut) = _pushCollectedFundGivenOut(address(this), poolAmountIn, tokenOut, tokenAmountOut); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return tokenAmountOut; } function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn) external _lock_ _logs_ returns (uint poolAmountIn) { require(finalized, "!finalized"); require(_records[tokenOut].bound, "!bound"); require(tokenAmountOut <= bmul(_records[tokenOut].balance, BConst.MAX_OUT_RATIO), ">maxORat"); Record storage outRecord = _records[tokenOut]; poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, swapFee, exitFee ); require(poolAmountIn != 0, "errMathAprox"); require(poolAmountIn <= maxPoolAmountIn, "<limIn"); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); uint _exitFee = bmul(poolAmountIn, exitFee); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); uint _collectedFeeAmount = _pushCollectedFundGivenIn(address(this), poolAmountIn); _burnPoolShare(bsub(bsub(poolAmountIn, _exitFee), _collectedFeeAmount)); _pushPoolShare(factory, _exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return poolAmountIn; } // == // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying(address erc20, address from, uint amount) internal { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "errErc20"); } function _pushUnderlying(address erc20, address to, uint amount) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "errErc20"); } function _pullPoolShare(address from, uint amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint amount) internal { _push(to, amount); } function _mintPoolShare(uint amount) internal { _mint(amount); } function _burnPoolShare(uint amount) internal { _burn(amount); } function _pushCollectedFundGivenOut(address _tokenIn, uint _tokenAmountIn, address _tokenOut, uint _tokenAmountOut) internal returns (uint subTokenAmountIn, uint tokenAmountOut) { subTokenAmountIn = 0; tokenAmountOut = _tokenAmountOut; if (collectedFee > 0) { address _collectedToken = IBFactory(factory).collectedToken(); if (_collectedToken == _tokenIn) { subTokenAmountIn = bdiv(bmul(_tokenAmountIn, collectedFee), BConst.BONE); _pushUnderlying(_tokenIn, factory, subTokenAmountIn); emit LOG_COLLECTED_FUND(_tokenIn, subTokenAmountIn); } else { uint _collectedFeeAmount = bdiv(bmul(_tokenAmountOut, collectedFee), BConst.BONE); _pushUnderlying(_tokenOut, factory, _collectedFeeAmount); tokenAmountOut = bsub(_tokenAmountOut, _collectedFeeAmount); emit LOG_COLLECTED_FUND(_tokenOut, _collectedFeeAmount); } } } // always push out _tokenIn (already have) function _pushCollectedFundGivenIn(address _tokenIn, uint _tokenAmountIn) internal returns (uint collectedFeeAmount) { collectedFeeAmount = 0; if (collectedFee > 0) { address _collectedToken = IBFactory(factory).collectedToken(); if (_collectedToken != address(0)) { collectedFeeAmount = bdiv(bmul(_tokenAmountIn, collectedFee), BConst.BONE); _pushUnderlying(_tokenIn, factory, collectedFeeAmount); emit LOG_COLLECTED_FUND(_tokenIn, collectedFeeAmount); } } } } // 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 disstributed 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/>. // Builds new BPools, logging their addresses and providing `isBPool(address) -> (bool)` contract BPoolCreator { function newBPool() external returns (BPool) { return new BPool(msg.sender); } }
********************************************************************************************* calcPoolOutGivenSingleIn pAo = poolAmountOut / \ tAi = tokenAmountIn / / wI \ \\ \ wI \ wI = tokenWeightIn | tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ tW = totalWeight pAo=|| \ \ \\ tW / | ^ tW | * pS - pS tBi = tokenBalanceIn \\ ------------------------------------- / / pS = poolSupply \\ tBi / / sF = swapFee (+ collectedFee)\ / / @dev Charge the trading fee for the proportion of tokenAi which is implicitly traded to the other pool tokens. That proportion is (1- weightTokenIn) tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure returns (uint poolAmountOut) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BConst.BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BConst.BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; }
2,076,632
[ 1, 12448, 2864, 1182, 6083, 5281, 382, 28524, 282, 293, 37, 83, 273, 2845, 6275, 1182, 540, 342, 4766, 2868, 521, 9079, 268, 37, 77, 273, 1147, 6275, 382, 3639, 342, 1377, 342, 540, 341, 45, 521, 1377, 1736, 4202, 521, 377, 341, 45, 521, 2868, 341, 45, 273, 1147, 6544, 382, 3639, 571, 268, 37, 77, 571, 404, 300, 747, 404, 300, 1493, 225, 571, 225, 272, 42, 747, 397, 268, 18808, 521, 565, 1493, 225, 521, 2398, 268, 59, 273, 2078, 6544, 377, 293, 37, 83, 33, 20081, 225, 521, 1377, 521, 377, 1736, 565, 268, 59, 342, 9079, 571, 3602, 268, 59, 282, 571, 225, 293, 55, 300, 293, 55, 225, 268, 18808, 273, 1147, 13937, 382, 1377, 1736, 225, 19134, 553, 342, 3639, 342, 2398, 293, 55, 273, 2845, 3088, 1283, 5411, 1736, 10792, 268, 18808, 9079, 342, 3639, 342, 2868, 272, 42, 273, 7720, 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, 7029, 2864, 1182, 6083, 5281, 382, 12, 203, 3639, 2254, 1147, 13937, 382, 16, 203, 3639, 2254, 1147, 6544, 382, 16, 203, 3639, 2254, 2845, 3088, 1283, 16, 203, 3639, 2254, 2078, 6544, 16, 203, 3639, 2254, 1147, 6275, 382, 16, 203, 3639, 2254, 7720, 14667, 203, 565, 262, 203, 565, 1071, 16618, 203, 565, 1135, 261, 11890, 2845, 6275, 1182, 13, 203, 565, 288, 203, 3639, 2254, 5640, 6544, 273, 324, 2892, 12, 2316, 6544, 382, 16, 2078, 6544, 1769, 203, 3639, 2254, 998, 1561, 273, 324, 16411, 12, 70, 1717, 12, 38, 9661, 18, 38, 5998, 16, 5640, 6544, 3631, 7720, 14667, 1769, 203, 3639, 2254, 1147, 6275, 382, 4436, 14667, 273, 324, 16411, 12, 2316, 6275, 382, 16, 324, 1717, 12, 38, 9661, 18, 38, 5998, 16, 998, 1561, 10019, 203, 203, 3639, 2254, 394, 1345, 13937, 382, 273, 324, 1289, 12, 2316, 13937, 382, 16, 1147, 6275, 382, 4436, 14667, 1769, 203, 3639, 2254, 1147, 382, 8541, 273, 324, 2892, 12, 2704, 1345, 13937, 382, 16, 1147, 13937, 382, 1769, 203, 203, 3639, 2254, 2845, 8541, 273, 9107, 543, 12, 2316, 382, 8541, 16, 5640, 6544, 1769, 203, 3639, 2254, 394, 2864, 3088, 1283, 273, 324, 16411, 12, 6011, 8541, 16, 2845, 3088, 1283, 1769, 203, 3639, 2845, 6275, 1182, 273, 324, 1717, 12, 2704, 2864, 3088, 1283, 16, 2845, 3088, 1283, 1769, 203, 3639, 327, 2845, 6275, 1182, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xc1dD3F011290F212227170F0D02F511EBF57E433/sources/modules/erc20/contracts/ERC20.sol
Cannot overflow because minting prevents overflow of totalSupply, and sum of user balances == totalSupply.
function _transfer(address owner_, address recipient_, uint256 amount_) internal { balanceOf[owner_] -= amount_; emit Transfer(owner_, recipient_, amount_); }
3,935,123
[ 1, 4515, 9391, 2724, 312, 474, 310, 17793, 9391, 434, 2078, 3088, 1283, 16, 471, 2142, 434, 729, 324, 26488, 422, 2078, 3088, 1283, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 3410, 67, 16, 1758, 8027, 67, 16, 2254, 5034, 3844, 67, 13, 2713, 288, 203, 3639, 11013, 951, 63, 8443, 67, 65, 3947, 3844, 67, 31, 203, 203, 203, 3639, 3626, 12279, 12, 8443, 67, 16, 8027, 67, 16, 3844, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "../../fixins/FixinERC1155Spender.sol"; import "../../storage/LibCommonNftOrdersStorage.sol"; import "../../storage/LibERC1155OrdersStorage.sol"; import "../interfaces/IERC1155OrdersFeature.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./NFTOrders.sol"; /// @dev Feature for interacting with ERC1155 orders. contract ERC1155OrdersFeature is IERC1155OrdersFeature, FixinERC1155Spender, NFTOrders { using LibNFTOrder for LibNFTOrder.ERC1155SellOrder; using LibNFTOrder for LibNFTOrder.ERC1155BuyOrder; using LibNFTOrder for LibNFTOrder.NFTSellOrder; using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev The magic return value indicating the success of a `onERC1155Received`. bytes4 private constant ERC1155_RECEIVED_MAGIC_BYTES = this.onERC1155Received.selector; constructor(IEtherToken weth) NFTOrders(weth) { } /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes memory callbackData ) public override { _sellERC1155( buyOrder, signature, SellParams( erc1155SellAmount, erc1155TokenId, unwrapNativeToken, msg.sender, // taker msg.sender, // owner callbackData ) ); } /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. function buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 erc1155BuyAmount ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buyERC1155(sellOrder, signature, erc1155BuyAmount); if (address(this).balance != ethBalanceBefore) { // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } } function buyERC1155Ex( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, address taker, uint128 erc1155BuyAmount, bytes memory callbackData ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buyERC1155Ex( sellOrder, signature, BuyParams( erc1155BuyAmount, msg.value, taker, callbackData ) ); if (address(this).balance != ethBalanceBefore) { // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } } /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC1155Order(uint256 orderNonce) public override { // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (orderNonce & 255); // Update order cancellation bit vector to indicate that the order // has been cancelled/filled by setting the designated bit to 1. LibERC1155OrdersStorage.getStorage().orderCancellationByMaker [msg.sender][uint248(orderNonce >> 8)] |= flag; emit ERC1155OrderCancelled(msg.sender, orderNonce); } /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC1155Orders(uint256[] calldata orderNonces) external override { for (uint256 i = 0; i < orderNonces.length; i++) { cancelERC1155Order(orderNonces[i]); } } /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155FillAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155s( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, uint128[] calldata erc1155FillAmounts, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == erc1155FillAmounts.length, "ERC1155OrdersFeature::batchBuyERC1155s/ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buyERC1155 reverts. _buyERC1155(sellOrders[i], signatures[i], erc1155FillAmounts[i]); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `buyERC1155FromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this.buyERC1155FromProxy.selector, sellOrders[i], signatures[i], erc1155FillAmounts[i] ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } function batchBuyERC1155sEx( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, address[] calldata takers, uint128[] calldata erc1155FillAmounts, bytes[] memory callbackData, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == takers.length && length == erc1155FillAmounts.length && length == callbackData.length, "ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buyERC1155Ex reverts. _buyERC1155Ex( sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `buyERC1155ExFromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this.buyERC1155ExFromProxy.selector, sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } // @Note `buyERC1155FromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function buyERC1155FromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) external payable { require(_implementation != address(this), "MUST_CALL_FROM_PROXY"); _buyERC1155(sellOrder, signature, buyAmount); } // @Note `buyERC1155ExFromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function buyERC1155ExFromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) external payable { require(_implementation != address(this), "MUST_CALL_FROM_PROXY"); _buyERC1155Ex(sellOrder, signature, params); } /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if /// a valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC1155 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param tokenId The ID of the asset being transferred. /// @param value The amount being transferred. /// @param data Additional data with no specified format. If a /// valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0xf23a6e61), /// indicating that the callback succeeded. function onERC1155Received( address operator, address /* from */, uint256 tokenId, uint256 value, bytes calldata data ) external override returns (bytes4 success) { // Decode the order, signature, and `unwrapNativeToken` from // `data`. If `data` does not encode such parameters, this // will throw. ( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken ) = abi.decode( data, (LibNFTOrder.ERC1155BuyOrder, LibSignature.Signature, bool) ); // `onERC1155Received` is called by the ERC1155 token contract. // Check that it matches the ERC1155 token in the order. if (msg.sender != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH"); } require(value <= type(uint128).max); _sellERC1155( buyOrder, signature, SellParams( uint128(value), tokenId, unwrapNativeToken, operator, // taker address(this), // owner (we hold the NFT currently) new bytes(0) // No taker callback ) ); return ERC1155_RECEIVED_MAGIC_BYTES; } /// @dev Approves an ERC1155 sell order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 sell order. function preSignERC1155SellOrder(LibNFTOrder.ERC1155SellOrder memory order) public override { require(order.maker == msg.sender, "ONLY_MAKER"); uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]; require(hashNonce < type(uint128).max); bytes32 orderHash = getERC1155SellOrderHash(order); LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned = uint128(hashNonce + 1); emit ERC1155SellOrderPreSigned( order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc1155Token, order.erc1155TokenId, order.erc1155TokenAmount ); } /// @dev Approves an ERC1155 buy order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 buy order. function preSignERC1155BuyOrder(LibNFTOrder.ERC1155BuyOrder memory order) public override { require(order.maker == msg.sender, "ONLY_MAKER"); uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]; require(hashNonce < type(uint128).max, "HASH_NONCE_OUTSIDE"); bytes32 orderHash = getERC1155BuyOrderHash(order); LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned = uint128(hashNonce + 1); emit ERC1155BuyOrderPreSigned( order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc1155Token, order.erc1155TokenId, order.erc1155TokenProperties, order.erc1155TokenAmount ); } // Core settlement logic for selling an ERC1155 asset. // Used by `sellERC1155` and `onERC1155Received`. function _sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) private { (uint256 erc20FillAmount, bytes32 orderHash) = _sellNFT( buyOrder.asNFTBuyOrder(), signature, params ); emit ERC1155BuyOrderFilled( buyOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(buyOrder.erc20Token)), (params.tokenId << 160) | uint160(buyOrder.erc1155Token), params.sellAmount, orderHash ); } // Core settlement logic for buying an ERC1155 asset. // Used by `buyERC1155` and `batchBuyERC1155s`. function _buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal { (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFT( sellOrder.asNFTSellOrder(), signature, buyAmount ); emit ERC1155SellOrderFilled( sellOrder.maker, msg.sender, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), buyAmount, orderHash ); } function _buyERC1155Ex( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal { if (params.taker == address(0)) { params.taker = msg.sender; } else { require(params.taker != address(this), "_buy1155Ex/TAKER_CANNOT_SELF"); } (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFTEx( sellOrder.asNFTSellOrder(), signature, params ); emit ERC1155SellOrderFilled( sellOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), params.buyAmount, orderHash ); } /// @dev Checks whether the given signature is valid for the /// the given ERC1155 sell order. Reverts if not. /// @param order The ERC1155 sell order. /// @param signature The signature to validate. function validateERC1155SellOrderSignature( LibNFTOrder.ERC1155SellOrder memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC1155SellOrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Checks whether the given signature is valid for the /// the given ERC1155 buy order. Reverts if not. /// @param order The ERC1155 buy order. /// @param signature The signature to validate. function validateERC1155BuyOrderSignature( LibNFTOrder.ERC1155BuyOrder memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC1155BuyOrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature( bytes32 orderHash, LibSignature.Signature memory signature, address maker ) internal override view { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { require( LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned == LibCommonNftOrdersStorage.getStorage().hashNonces[maker] + 1, "PRESIGNED_INVALID_SIGNER" ); } else { require( maker != address(0) && maker == ecrecover(orderHash, signature.v, signature.r, signature.s), "INVALID_SIGNER_ERROR" ); } } /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferNFTAssetFrom( address token, address from, address to, uint256 tokenId, uint256 amount ) internal override { _transferERC1155AssetFrom(token, from, to, tokenId, amount); } /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState( LibNFTOrder.NFTSellOrder memory /* order */, bytes32 orderHash, uint128 fillAmount ) internal override { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); uint128 filledAmount = stor.orderState[orderHash].filledAmount; // Filled amount should never overflow 128 bits require(filledAmount + fillAmount > filledAmount); stor.orderState[orderHash].filledAmount = filledAmount + fillAmount; } /// @dev Get the order info for an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderInfo Infor about the order. function getERC1155SellOrderInfo(LibNFTOrder.ERC1155SellOrder memory order) public override view returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = getERC1155SellOrderHash(order); // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the order info for an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderInfo Infor about the order. function getERC1155BuyOrderInfo(LibNFTOrder.ERC1155BuyOrder memory order) public override view returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = getERC1155BuyOrderHash(order); // Only buy orders with `erc1155TokenId` == 0 can be property // orders. if (order.erc1155TokenId != 0 && order.erc1155TokenProperties.length > 0) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. if (address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the EIP-712 hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderHash The order hash. function getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155SellOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } /// @dev Get the EIP-712 hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderHash The order hash. function getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155BuyOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } /// @dev Get the order nonce status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC1155OrderNonceStatusBitVector(address maker, uint248 nonceRange) external override view returns (uint256) { return LibERC1155OrdersStorage.getStorage().orderCancellationByMaker[maker][nonceRange]; } /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155SellOrderInfo(nftSellOrder.asERC1155SellOrder()); } /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155BuyOrderInfo(nftBuyOrder.asERC1155BuyOrder()); } /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC1155Orders( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature ) public override returns (uint256 profit) { // The ERC1155 tokens must match if (sellOrder.erc1155Token != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH_ERROR"); } LibNFTOrder.NFTSellOrder memory sellNFTOrder = sellOrder.asNFTSellOrder(); LibNFTOrder.NFTBuyOrder memory buyNFTOrder = buyOrder.asNFTBuyOrder(); LibNFTOrder.OrderInfo memory sellOrderInfo = getERC1155SellOrderInfo(sellOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = getERC1155BuyOrderInfo(buyOrder); bool isEnglishAuction = (sellOrder.expiry >> 252 == 2); if (isEnglishAuction) { require( sellOrderInfo.orderAmount == sellOrderInfo.remainingAmount && sellOrderInfo.orderAmount == buyOrderInfo.orderAmount && sellOrderInfo.orderAmount == buyOrderInfo.remainingAmount, "UNMATCH_ORDER_AMOUNT" ); } _validateSellOrder( sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker ); _validateBuyOrder( buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc1155TokenId ); // fillAmount = min(sellOrder.remainingAmount, buyOrder.remainingAmount) uint128 erc1155FillAmount = sellOrderInfo.remainingAmount < buyOrderInfo.remainingAmount ? sellOrderInfo.remainingAmount : buyOrderInfo.remainingAmount; // Reset sellOrder.erc20TokenAmount if (erc1155FillAmount != sellOrderInfo.orderAmount) { sellOrder.erc20TokenAmount = _ceilDiv( sellOrder.erc20TokenAmount * erc1155FillAmount, sellOrderInfo.orderAmount ); } // Reset buyOrder.erc20TokenAmount if (erc1155FillAmount != buyOrderInfo.orderAmount) { buyOrder.erc20TokenAmount = buyOrder.erc20TokenAmount * erc1155FillAmount / buyOrderInfo.orderAmount; } if (isEnglishAuction) { _resetEnglishAuctionTokenAmountAndFees( sellNFTOrder, buyOrder.erc20TokenAmount, erc1155FillAmount, sellOrderInfo.orderAmount ); } // Mark both orders as filled. _updateOrderState(sellNFTOrder, sellOrderInfo.orderHash, erc1155FillAmount); _updateOrderState(buyNFTOrder.asNFTSellOrder(), buyOrderInfo.orderHash, erc1155FillAmount); // The difference in ERC20 token amounts is the spread. uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount; // Transfer the ERC1155 asset from seller to buyer. _transferERC1155AssetFrom( sellOrder.erc1155Token, sellOrder.maker, buyOrder.maker, sellOrder.erc1155TokenId, erc1155FillAmount ); // Handle the ERC20 side of the order: if ( address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH ) { // The sell order specifies ETH, while the buy order specifies WETH. // The orders are still compatible with one another, but we'll have // to unwrap the WETH on behalf of the buyer. // Step 1: Transfer WETH from the buyer to the EP. // Note that we transfer `buyOrder.erc20TokenAmount`, which // is the amount the buyer signaled they are willing to pay // for the ERC1155 asset, which may be more than the seller's // ask. _transferERC20TokensFrom( WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount ); // Step 2: Unwrap the WETH into ETH. We unwrap the entire // `buyOrder.erc20TokenAmount`. // The ETH will be used for three purposes: // - To pay the seller // - To pay fees for the sell order // - Any remaining ETH will be sent to // `msg.sender` as profit. WETH.withdraw(buyOrder.erc20TokenAmount); // Step 3: Pay the seller (in ETH). _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount); // Step 4: Pay fees for the buy order. Note that these are paid // in _WETH_ by the _buyer_. By signing the buy order, the // buyer signals that they are willing to spend a total // of `erc20TokenAmount` _plus_ fees, all denominated in // the `erc20Token`, which in this case is WETH. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 5: Pay fees for the sell order. The `erc20Token` of the // sell order is ETH, so the fees are paid out in ETH. // There should be `spread` wei of ETH remaining in the // EP at this point, which we will use ETH to pay the // sell order fees. uint256 sellOrderFees = _payFees( sellNFTOrder, address(this), // payer erc1155FillAmount, sellOrderInfo.orderAmount, true // useNativeToken ); // Step 6: The spread less the sell order fees is the amount of ETH // remaining in the EP that can be sent to `msg.sender` as // the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferEth(payable(msg.sender), profit); } } else { // ERC20 tokens must match if (sellOrder.erc20Token != buyOrder.erc20Token) { revert("ERC20_TOKEN_MISMATCH"); } // Step 1: Transfer the ERC20 token from the buyer to the seller. // Note that we transfer `sellOrder.erc20TokenAmount`, which // is at most `buyOrder.erc20TokenAmount`. _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount ); // Step 2: Pay fees for the buy order. Note that these are paid // by the buyer. By signing the buy order, the buyer signals // that they are willing to spend a total of // `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 3: Pay fees for the sell order. These are paid by the buyer // as well. After paying these fees, we may have taken more // from the buyer than they agreed to in the buy order. If // so, we revert in the following step. uint256 sellOrderFees = _payFees( sellNFTOrder, buyOrder.maker, // payer erc1155FillAmount, sellOrderInfo.orderAmount, false // useNativeToken ); // Step 4: We calculate the profit as: // profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees // = spread - sellOrderFees // I.e. the buyer would've been willing to pay up to `profit` // more to buy the asset, so instead that amount is sent to // `msg.sender` as the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, msg.sender, profit ); } } _emitEventSellOrderFilled( sellOrder, buyOrder.maker, // taker erc1155FillAmount, sellOrderInfo.orderHash ); _emitEventBuyOrderFilled( buyOrder, sellOrder.maker, // taker sellOrder.erc1155TokenId, erc1155FillAmount, buyOrderInfo.orderHash ); } function _emitEventSellOrderFilled( LibNFTOrder.ERC1155SellOrder memory sellOrder, address taker, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155SellOrderFilled( sellOrder.maker, taker, (sellOrder.erc20TokenAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), erc1155FillAmount, orderHash ); } function _emitEventBuyOrderFilled( LibNFTOrder.ERC1155BuyOrder memory buyOrder, address taker, uint256 erc1155TokenId, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155BuyOrderFilled( buyOrder.maker, taker, (buyOrder.erc20TokenAmount << 160) | uint160(address(buyOrder.erc20Token)), (erc1155TokenId << 160) | uint160(buyOrder.erc1155Token), erc1155FillAmount, orderHash ); } /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC1155Orders( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibNFTOrder.ERC1155BuyOrder[] memory buyOrders, LibSignature.Signature[] memory sellOrderSignatures, LibSignature.Signature[] memory buyOrderSignatures ) public override returns (uint256[] memory profits, bool[] memory successes) { require( sellOrders.length == buyOrders.length && sellOrderSignatures.length == buyOrderSignatures.length && sellOrders.length == sellOrderSignatures.length ); profits = new uint256[](sellOrders.length); successes = new bool[](sellOrders.length); for (uint256 i = 0; i < sellOrders.length; i++) { bytes memory returnData; // Delegatecall `matchERC1155Orders` to catch reverts while // preserving execution context. (successes[i], returnData) = _implementation.delegatecall( abi.encodeWithSelector( this.matchERC1155Orders.selector, sellOrders[i], buyOrders[i], sellOrderSignatures[i], buyOrderSignatures[i] ) ); if (successes[i]) { // If the matching succeeded, record the profit. (uint256 profit) = abi.decode(returnData, (uint256)); profits[i] = profit; } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev Helpers for moving ERC1155 assets around. abstract contract FixinERC1155Spender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers an ERC1155 asset from `owner` to `to`. /// @param token The address of the ERC1155 token contract. /// @param owner The owner of the asset. /// @param to The recipient of the asset. /// @param tokenId The token ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferERC1155AssetFrom( address token, address owner, address to, uint256 tokenId, uint256 amount ) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for safeTransferFrom(address,address,uint256,uint256,bytes) mstore(ptr, 0xf242432a00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), tokenId) mstore(add(ptr, 0x64), amount) mstore(add(ptr, 0x84), 0xa0) mstore(add(ptr, 0xa4), 0) success := call( gas(), and(token, ADDRESS_MASK), 0, ptr, 0xc4, 0, 0 ) } require(success != 0, "_transferERC1155/TRANSFER_FAILED"); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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.8.13; import "./LibStorage.sol"; library LibCommonNftOrdersStorage { /// @dev Storage bucket for this feature. struct Storage { /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) hashNonces; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_COMMON_NFT_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "./LibStorage.sol"; /// @dev Storage helpers for `ERC1155OrdersFeature`. library LibERC1155OrdersStorage { struct OrderState { // The amount (denominated in the ERC1155 asset) // that the order has been filled by. uint128 filledAmount; // Whether the order has been pre-signed. uint128 preSigned; } /// @dev Storage bucket for this feature. struct Storage { // Mapping from order hash to order state: mapping(bytes32 => OrderState) orderState; // maker => nonce range => order cancellation bit vector mapping(address => mapping(uint248 => uint256)) orderCancellationByMaker; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_ERC1155_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./IERC1155OrdersEvent.sol"; /// @dev Feature for interacting with ERC1155 orders. interface IERC1155OrdersFeature is IERC1155OrdersEvent { /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellERC1155( LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes calldata callbackData ) external; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. function buyERC1155( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, uint128 erc1155BuyAmount ) external payable; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param taker The address to receive ERC1155. If this parameter /// is zero, transfer ERC1155 to `msg.sender`. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC1155 asset has been transferred to `msg.sender` /// but before transferring the ERC20 tokens to the seller. /// Native tokens acquired during the callback can be used /// to fill the order. function buyERC1155Ex( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, address taker, uint128 erc1155BuyAmount, bytes calldata callbackData ) external payable; /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC1155Order(uint256 orderNonce) external; /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC1155Orders(uint256[] calldata orderNonces) external; /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155TokenAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155s( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, uint128[] calldata erc1155TokenAmounts, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155TokenAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param takers The address to receive ERC1155. /// @param callbackData The data (if any) to pass to the taker /// callback for each order. Refer to the `callbackData` /// parameter to for `buyERC1155`. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155sEx( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, address[] calldata takers, uint128[] calldata erc1155TokenAmounts, bytes[] calldata callbackData, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if /// a valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC1155 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param from The address which previously owned the token. /// @param tokenId The ID of the asset being transferred. /// @param value The amount being transferred. /// @param data Additional data with no specified format. If a /// valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0xf23a6e61), /// indicating that the callback succeeded. function onERC1155Received( address operator, address from, uint256 tokenId, uint256 value, bytes calldata data ) external returns (bytes4 success); /// @dev Approves an ERC1155 sell order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 sell order. function preSignERC1155SellOrder(LibNFTOrder.ERC1155SellOrder calldata order) external; /// @dev Approves an ERC1155 buy order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 buy order. function preSignERC1155BuyOrder(LibNFTOrder.ERC1155BuyOrder calldata order) external; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 sell order. Reverts if not. /// @param order The ERC1155 sell order. /// @param signature The signature to validate. function validateERC1155SellOrderSignature( LibNFTOrder.ERC1155SellOrder calldata order, LibSignature.Signature calldata signature ) external view; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 buy order. Reverts if not. /// @param order The ERC1155 buy order. /// @param signature The signature to validate. function validateERC1155BuyOrderSignature( LibNFTOrder.ERC1155BuyOrder calldata order, LibSignature.Signature calldata signature ) external view; /// @dev Get the order info for an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderInfo Infor about the order. function getERC1155SellOrderInfo(LibNFTOrder.ERC1155SellOrder calldata order) external view returns (LibNFTOrder.OrderInfo memory orderInfo); /// @dev Get the order info for an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderInfo Infor about the order. function getERC1155BuyOrderInfo(LibNFTOrder.ERC1155BuyOrder calldata order) external view returns (LibNFTOrder.OrderInfo memory orderInfo); /// @dev Get the EIP-712 hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderHash The order hash. function getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the EIP-712 hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderHash The order hash. function getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the order nonce status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC1155OrderNonceStatusBitVector(address maker, uint248 nonceRange) external view returns (uint256); /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC1155Orders( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata sellOrderSignature, LibSignature.Signature calldata buyOrderSignature ) external returns (uint256 profit); /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC1155Orders( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibNFTOrder.ERC1155BuyOrder[] calldata buyOrders, LibSignature.Signature[] calldata sellOrderSignatures, LibSignature.Signature[] calldata buyOrderSignatures ) external returns (uint256[] memory profits, bool[] memory successes); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../vendor/IPropertyValidator.sol"; /// @dev A library for common NFT order operations. library LibNFTOrder { enum OrderStatus { INVALID, FILLABLE, UNFILLABLE, EXPIRED } struct Property { IPropertyValidator propertyValidator; bytes propertyData; } struct Fee { address recipient; uint256 amount; bytes feeData; } struct NFTSellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; } // All fields except `nftProperties` align // with those of NFTSellOrder struct NFTBuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; } // All fields except `erc1155TokenAmount` align // with those of NFTSellOrder struct ERC1155SellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } // All fields except `erc1155TokenAmount` align // with those of NFTBuyOrder struct ERC1155BuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; Property[] erc1155TokenProperties; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } struct OrderInfo { bytes32 orderHash; OrderStatus status; // `orderAmount` is 1 for all ERC721Orders, and // `erc1155TokenAmount` for ERC1155Orders. uint128 orderAmount; // The remaining amount of the ERC721/ERC1155 asset // that can be filled for the order. uint128 remainingAmount; } // The type hash for sell orders, which is: // keccak256(abi.encodePacked( // "NFTSellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _NFT_SELL_ORDER_TYPE_HASH = 0xed676c7f3e8232a311454799b1cf26e75b4abc90c9bf06c9f7e8e79fcc7fe14d; // The type hash for buy orders, which is: // keccak256(abi.encodePacked( // "NFTBuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "Property[] nftProperties,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _NFT_BUY_ORDER_TYPE_HASH = 0xa525d336300f566329800fcbe82fd263226dc27d6c109f060d9a4a364281521c; // The type hash for ERC1155 sell orders, which is: // keccak256(abi.encodePacked( // "ERC1155SellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda; // The type hash for ERC1155 buy orders, which is: // keccak256(abi.encodePacked( // "ERC1155BuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "Property[] erc1155TokenProperties,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _ERC_1155_BUY_ORDER_TYPE_HASH = 0x1a6eaae1fbed341e0974212ec17f035a9d419cadc3bf5154841cbf7fd605ba48; // keccak256(abi.encodePacked( // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _FEE_TYPE_HASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; // keccak256(abi.encodePacked( // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; // keccak256(""); bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // address(0), // keccak256("") // )))); bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; function asNFTSellOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := nftBuyOrder } } function asNFTSellOrder(ERC1155SellOrder memory erc1155SellOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := erc1155SellOrder } } function asNFTBuyOrder(ERC1155BuyOrder memory erc1155BuyOrder) internal pure returns (NFTBuyOrder memory order) { assembly { order := erc1155BuyOrder } } function asERC1155SellOrder(NFTSellOrder memory nftSellOrder) internal pure returns (ERC1155SellOrder memory order) { assembly { order := nftSellOrder } } function asERC1155BuyOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (ERC1155BuyOrder memory order) { assembly { order := nftBuyOrder } } // @dev Get the struct hash of an sell order. /// @param order The sell order. /// @return structHash The struct hash of the order. function getNFTSellOrderStructHash(NFTSellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 288) // order + (32 * 9) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 352 /* 32 * 11 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an buy order. /// @param order The buy order. /// @return structHash The struct hash of the order. function getNFTBuyOrderStructHash(NFTBuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.nftProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // propertiesHash, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return structHash The struct hash of the order. function getERC1155SellOrderStructHash(ERC1155SellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return structHash The struct hash of the order. function getERC1155BuyOrderStructHash(ERC1155BuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // propertiesHash, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 352) // order + (32 * 11) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 416 /* 32 * 13 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } // Hashes the `properties` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) { uint256 numProperties = properties.length; // We give `properties.length == 0` and `properties.length == 1` // special treatment because we expect these to be the most common. if (numProperties == 0) { propertiesHash = _EMPTY_ARRAY_KECCAK256; } else if (numProperties == 1) { Property memory property = properties[0]; if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) { propertiesHash = _NULL_PROPERTY_STRUCT_HASH; } else { // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // properties[0].propertyValidator, // keccak256(properties[0].propertyData) // )))); bytes32 dataHash = keccak256(property.propertyData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _PROPERTY_TYPE_HASH) // property.propertyValidator mstore(add(mem, 32), and(ADDRESS_MASK, mload(property))) // keccak256(property.propertyData) mstore(add(mem, 64), dataHash) mstore(mem, keccak256(mem, 96)) propertiesHash := keccak256(mem, 32) } } } else { bytes32[] memory propertyStructHashArray = new bytes32[](numProperties); for (uint256 i = 0; i < numProperties; i++) { propertyStructHashArray[i] = keccak256(abi.encode( _PROPERTY_TYPE_HASH, properties[i].propertyValidator, keccak256(properties[i].propertyData))); } assembly { propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32)) } } } // Hashes the `fees` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) { uint256 numFees = fees.length; // We give `fees.length == 0` and `fees.length == 1` // special treatment because we expect these to be the most common. if (numFees == 0) { feesHash = _EMPTY_ARRAY_KECCAK256; } else if (numFees == 1) { // feesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _FEE_TYPE_HASH, // fees[0].recipient, // fees[0].amount, // keccak256(fees[0].feeData) // )))); Fee memory fee = fees[0]; bytes32 dataHash = keccak256(fee.feeData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _FEE_TYPE_HASH) // fee.recipient mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee))) // fee.amount mstore(add(mem, 64), mload(add(fee, 32))) // keccak256(fee.feeData) mstore(add(mem, 96), dataHash) mstore(mem, keccak256(mem, 128)) feesHash := keccak256(mem, 32) } } else { bytes32[] memory feeStructHashArray = new bytes32[](numFees); for (uint256 i = 0; i < numFees; i++) { feeStructHashArray[i] = keccak256(abi.encode(_FEE_TYPE_HASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData))); } assembly { feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32)) } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev A library for validating signatures. library LibSignature { /// @dev Allowed signature types. enum SignatureType { EIP712, PRESIGNED } /// @dev Encoded EC signature. struct Signature { // How to validate the signature. SignatureType signatureType; // EC Signature data. uint8 v; // EC Signature data. bytes32 r; // EC Signature data. bytes32 s; } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../fixins/FixinEIP712.sol"; import "../../fixins/FixinTokenSpender.sol"; import "../../vendor/IEtherToken.sol"; import "../../vendor/IFeeRecipient.sol"; import "../../vendor/ITakerCallback.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNFTOrder.sol"; /// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders abstract contract NFTOrders is FixinEIP712, FixinTokenSpender { using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev Native token pseudo-address. address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The WETH token contract. IEtherToken internal immutable WETH; /// @dev The implementation address of this feature. address internal immutable _implementation; /// @dev The magic return value indicating the success of a `receiveZeroExFeeCallback`. bytes4 private constant FEE_CALLBACK_MAGIC_BYTES = IFeeRecipient.receiveZeroExFeeCallback.selector; /// @dev The magic return value indicating the success of a `zeroExTakerCallback`. bytes4 private constant TAKER_CALLBACK_MAGIC_BYTES = ITakerCallback.zeroExTakerCallback.selector; constructor(IEtherToken weth) { require(address(weth) != address(0), "WETH_ADDRESS_ERROR"); WETH = weth; // Remember this feature's original address. _implementation = address(this); } struct SellParams { uint128 sellAmount; uint256 tokenId; bool unwrapNativeToken; address taker; address currentNftOwner; bytes takerCallbackData; } struct BuyParams { uint128 buyAmount; uint256 ethAvailable; address taker; bytes takerCallbackData; } // Core settlement logic for selling an NFT asset. function _sellNFT( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId); // Check amount. if (params.sellAmount > orderInfo.remainingAmount) { revert("_sellNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(buyOrder.asNFTSellOrder(), orderInfo.orderHash, params.sellAmount); // Calculate erc20 pay amount. erc20FillAmount = (params.sellAmount == orderInfo.orderAmount) ? buyOrder.erc20TokenAmount : buyOrder.erc20TokenAmount * params.sellAmount / orderInfo.orderAmount; if (params.unwrapNativeToken) { // The ERC20 token must be WETH for it to be unwrapped. require(buyOrder.erc20Token == WETH, "_sellNFT/ERC20_TOKEN_MISMATCH_ERROR"); // Transfer the WETH from the maker to the Exchange Proxy // so we can unwrap it before sending it to the seller. // TODO: Probably safe to just use WETH.transferFrom for some // small gas savings _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount); // Unwrap WETH into ETH. WETH.withdraw(erc20FillAmount); // Send ETH to the seller. _transferEth(payable(params.taker), erc20FillAmount); } else { // Transfer the ERC20 token from the buyer to the seller. _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount); } if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_sellNFT/CANNOT_CALLBACK_SELF"); // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_sellNFT/CALLBACK_FAILED"); } // Transfer the NFT asset to the buyer. // If this function is called from the // `onNFTReceived` callback the Exchange Proxy // holds the asset. Otherwise, transfer it from // the seller. _transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount); // The buyer pays the order fees. _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false); } // Core settlement logic for buying an NFT asset. function _buyNFT( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, msg.sender); // Check amount. if (buyAmount > orderInfo.remainingAmount) { revert("_buyNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, buyAmount); // Calculate erc20 pay amount. erc20FillAmount = (buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer (`msg.sender`). _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, buyAmount); if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), buyAmount, orderInfo.orderAmount, true); } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, buyAmount, orderInfo.orderAmount, false); } } function _buyNFTEx( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, params.taker); // Check amount. if (params.buyAmount > orderInfo.remainingAmount) { revert("_buyNFTEx/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount); // Dutch Auction if (sellOrder.expiry >> 252 == 1) { uint256 count = (sellOrder.expiry >> 64) & 0xffffffff; if (count > 0) { _resetDutchAuctionTokenAmountAndFees(sellOrder, count); } } // Calculate erc20 pay amount. erc20FillAmount = (params.buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * params.buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer. _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, params.taker, sellOrder.nftId, params.buyAmount); uint256 ethAvailable = params.ethAvailable; if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_buyNFTEx/CANNOT_CALLBACK_SELF"); uint256 ethBalanceBeforeCallback = address(this).balance; // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Update `ethAvailable` with amount acquired during // the callback ethAvailable += address(this).balance - ethBalanceBeforeCallback; // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_buyNFTEx/CALLBACK_FAILED"); } if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { uint256 totalPaid = erc20FillAmount + _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable < totalPaid) { // Transfer WETH from the buyer to this contract. uint256 withDrawAmount = totalPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), withDrawAmount); // Unwrap WETH into ETH. WETH.withdraw(withDrawAmount); } // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else if (sellOrder.erc20Token == WETH) { uint256 totalFeesPaid = _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable > totalFeesPaid) { uint256 depositAmount = ethAvailable - totalFeesPaid; if (depositAmount < erc20FillAmount) { // Transfer WETH from the buyer to this contract. _transferERC20TokensFrom(WETH, msg.sender, address(this), (erc20FillAmount - depositAmount)); } else { depositAmount = erc20FillAmount; } // Wrap ETH. WETH.deposit{value: depositAmount}(); // Transfer WETH to the seller. _transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // Transfer WETH from the buyer to the seller. _transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount); if (ethAvailable > 0) { if (ethAvailable < totalFeesPaid) { // Transfer WETH from the buyer to this contract. uint256 value = totalFeesPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), value); // Unwrap WETH into ETH. WETH.withdraw(value); } // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // The buyer pays fees using WETH. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } function _validateSellOrder( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker ) internal view { // Taker must match the order taker, if one is specified. require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker); } function _validateBuyOrder( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker, uint256 tokenId ) internal view { // The ERC20 token cannot be ETH. require(address(buyOrder.erc20Token) != NATIVE_TOKEN_ADDRESS, "_validateBuyOrder/TOKEN_MISMATCH"); // Taker must match the order taker, if one is specified. require(buyOrder.taker == address(0) || buyOrder.taker == taker, "_validateBuyOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check that the asset with the given token ID satisfies the properties // specified by the order. _validateOrderProperties(buyOrder, tokenId); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, buyOrder.maker); } function _resetDutchAuctionTokenAmountAndFees(LibNFTOrder.NFTSellOrder memory order, uint256 count) internal view { require(count <= 100000000, "COUNT_OUT_OF_SIDE"); uint256 listingTime = (order.expiry >> 32) & 0xffffffff; uint256 denominator = ((order.expiry & 0xffffffff) - listingTime) * 100000000; uint256 multiplier = (block.timestamp - listingTime) * count; // Reset erc20TokenAmount uint256 amount = order.erc20TokenAmount; order.erc20TokenAmount = amount - amount * multiplier / denominator; // Reset fees for (uint256 i = 0; i < order.fees.length; i++) { amount = order.fees[i].amount; order.fees[i].amount = amount - amount * multiplier / denominator; } } function _resetEnglishAuctionTokenAmountAndFees( LibNFTOrder.NFTSellOrder memory sellOrder, uint256 buyERC20Amount, uint256 fillAmount, uint256 orderAmount ) internal pure { uint256 sellOrderFees = _calcTotalFeesPaid(sellOrder.fees, fillAmount, orderAmount); uint256 sellTotalAmount = sellOrderFees + sellOrder.erc20TokenAmount; if (buyERC20Amount != sellTotalAmount) { uint256 spread = buyERC20Amount - sellTotalAmount; uint256 sum; // Reset fees if (sellTotalAmount > 0) { for (uint256 i = 0; i < sellOrder.fees.length; i++) { uint256 diff = spread * sellOrder.fees[i].amount / sellTotalAmount; sellOrder.fees[i].amount += diff; sum += diff; } } // Reset erc20TokenAmount sellOrder.erc20TokenAmount += spread - sum; } } function _ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // ceil(a / b) = floor((a + b - 1) / b) return (a + b - 1) / b; } function _calcTotalFeesPaid(LibNFTOrder.Fee[] memory fees, uint256 fillAmount, uint256 orderAmount) private pure returns (uint256 totalFeesPaid) { if (fillAmount == orderAmount) { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount; } } else { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount * fillAmount / orderAmount; } } return totalFeesPaid; } function _payFees( LibNFTOrder.NFTSellOrder memory order, address payer, uint128 fillAmount, uint128 orderAmount, bool useNativeToken ) internal returns (uint256 totalFeesPaid) { for (uint256 i = 0; i < order.fees.length; i++) { LibNFTOrder.Fee memory fee = order.fees[i]; uint256 feeFillAmount = (fillAmount == orderAmount) ? fee.amount : fee.amount * fillAmount / orderAmount; if (useNativeToken) { // Transfer ETH to the fee recipient. _transferEth(payable(fee.recipient), feeFillAmount); } else { if (feeFillAmount > 0) { // Transfer ERC20 token from payer to recipient. _transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount); } } // Note that the fee callback is _not_ called if zero // `feeData` is provided. If `feeData` is provided, we assume // the fee recipient is a contract that implements the // `IFeeRecipient` interface. if (fee.feeData.length > 0) { // Invoke the callback bytes4 callbackResult = IFeeRecipient(fee.recipient).receiveZeroExFeeCallback( useNativeToken ? NATIVE_TOKEN_ADDRESS : address(order.erc20Token), feeFillAmount, fee.feeData ); // Check for the magic success bytes require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "_payFees/CALLBACK_FAILED"); } // Sum the fees paid totalFeesPaid += feeFillAmount; } return totalFeesPaid; } function _validateOrderProperties(LibNFTOrder.NFTBuyOrder memory order, uint256 tokenId) internal view { // If no properties are specified, check that the given // `tokenId` matches the one specified in the order. if (order.nftProperties.length == 0) { require(tokenId == order.nftId, "_validateProperties/TOKEN_ID_ERR"); } else { // Validate each property for (uint256 i = 0; i < order.nftProperties.length; i++) { LibNFTOrder.Property memory property = order.nftProperties[i]; // `address(0)` is interpreted as a no-op. Any token ID // will satisfy a property with `propertyValidator == address(0)`. if (address(property.propertyValidator) != address(0)) { // Call the property validator and throw a descriptive error // if the call reverts. try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData) { } catch (bytes memory /* reason */) { revert("PROPERTY_VALIDATION_FAILED"); } } } } } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal virtual view; /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. Always /// 1 for ERC721 assets. function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 amount) internal virtual; /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param order The order that has been filled. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 orderHash, uint128 fillAmount) internal virtual; /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev Common storage helpers library LibStorage { /// @dev What to bit-shift a storage ID by to get its slot. /// This gives us a maximum of 2**128 inline fields in each bucket. uint256 constant STORAGE_ID_PROXY = 1 << 128; uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128; uint256 constant STORAGE_ID_OWNABLE = 3 << 128; uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128; uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128; uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; interface IERC1155OrdersEvent { /// @dev Emitted whenever an `ERC1155SellOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155SellOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted whenever an `ERC1155BuyOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155BuyOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted when an `ERC1155SellOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155SellOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, uint128 erc1155TokenAmount ); /// @dev Emitted when an `ERC1155BuyOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155BuyOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, LibNFTOrder.Property[] erc1155TokenProperties, uint128 erc1155TokenAmount ); /// @dev Emitted whenever an `ERC1155Order` is cancelled. /// @param maker The maker of the order. /// @param nonce The nonce of the order that was cancelled. event ERC1155OrderCancelled(address maker, uint256 nonce); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface IPropertyValidator { /// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`. /// Should revert if the asset does not satisfy the specified properties. /// @param tokenAddress The ERC721/ERC1155 token contract address. /// @param tokenId The ERC721/ERC1155 tokenId of the asset to check. /// @param propertyData Encoded properties or auxiliary data needed to perform the check. function validateProperty(address tokenAddress, uint256 tokenId, bytes calldata propertyData) external view; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev EIP712 helpers for features. abstract contract FixinEIP712 { bytes32 private constant DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant NAME = keccak256("ElementEx"); bytes32 private constant VERSION = keccak256("1.0.0"); uint256 private immutable CHAIN_ID; constructor() { uint256 chainId; assembly { chainId := chainid() } CHAIN_ID = chainId; } function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked(hex"1901", keccak256(abi.encode(DOMAIN, NAME, VERSION, CHAIN_ID, address(this))), structHash)); } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @dev Helpers for moving tokens around. abstract contract FixinTokenSpender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers ERC20 tokens from `owner` to `to`. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20TokensFrom(IERC20 token, address owner, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transferFrom(address,address,uint256) mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers ERC20 tokens from ourselves to `to`. /// @param token The token to spend. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20Tokens(IERC20 token, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transfer(address,uint256) mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x24), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers some amount of ETH to the given recipient and /// reverts if the transfer fails. /// @param recipient The recipient of the ETH. /// @param amount The amount of ETH to transfer. function _transferEth(address payable recipient, uint256 amount) internal { if (amount > 0) { (bool success,) = recipient.call{value: amount}(""); require(success, "_transferEth/TRANSFER_FAILED"); } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEtherToken is IERC20 { /// @dev Wrap ether. function deposit() external payable; /// @dev Unwrap ether. function withdraw(uint256 amount) external; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface IFeeRecipient { /// @dev A callback function invoked in the ERC721Feature for each ERC721 /// order fee that get paid. Integrators can make use of this callback /// to implement arbitrary fee-handling logic, e.g. splitting the fee /// between multiple parties. /// @param tokenAddress The address of the token in which the received fee is /// denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates /// that the fee was paid in the native token (e.g. ETH). /// @param amount The amount of the given token received. /// @param feeData Arbitrary data encoded in the `Fee` used by this callback. /// @return success The selector of this function (0x0190805e), /// indicating that the callback succeeded. function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface ITakerCallback { /// @dev A taker callback function invoked in ERC721OrdersFeature and /// ERC1155OrdersFeature between the maker -> taker transfer and /// the taker -> maker transfer. /// @param orderHash The hash of the order being filled when this /// callback is invoked. /// @param data Arbitrary data used by this callback. /// @return success The selector of this function, /// indicating that the callback succeeded. function zeroExTakerCallback(bytes32 orderHash, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } }
keccak256(abi.encodePacked( "Property(", "address propertyValidator,", "bytes propertyData", ")" ))
uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8;
1,499,119
[ 1, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 565, 315, 1396, 2932, 16, 3639, 315, 2867, 1272, 5126, 16, 3113, 3639, 315, 3890, 1272, 751, 3113, 565, 7310, 8623, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 3238, 5381, 389, 9900, 67, 2399, 67, 15920, 273, 374, 92, 26, 5540, 22, 8522, 28, 6564, 3247, 21, 7358, 5718, 5482, 27, 73, 21607, 7677, 25, 26881, 4449, 70, 23, 1727, 29, 74, 27, 74, 27, 3103, 7301, 311, 2992, 69, 24, 71, 5540, 70, 26, 72, 23, 13459, 9222, 73, 28, 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 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY886() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF698(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER57(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE343(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE196(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM951(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER641(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL12(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER192() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY886() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF698(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER57(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(_MSGSENDER192(), recipient, amount); return true; } function ALLOWANCE343(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE196(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, amount); return true; } function TRANSFERFROM951(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(sender, recipient, amount); _APPROVE501(sender, _MSGSENDER192(), _allowances[sender][_MSGSENDER192()].SUB39(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE73(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].ADD377(addedValue)); return true; } function DECREASEALLOWANCE445(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].SUB39(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER194(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB39(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD377(amount); emit TRANSFER641(sender, recipient, amount); } function _MINT845(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD377(amount); _balances[account] = _balances[account].ADD377(amount); emit TRANSFER641(address(0), account, amount); } function _BURN745(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB39(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB39(amount); emit TRANSFER641(account, address(0), amount); } function _APPROVE501(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL12(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; uint256 private TokenmaxSupply = 2500*10**18; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME395() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS28() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function MAXSUPPLY198() public view returns (uint256) { //inject NONSTANDARD NAMING return TokenmaxSupply; } } library SafeMath { function ADD377(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB39(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB39(a, b, "SafeMath: subtraction overflow"); } function SUB39(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL593(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV750(a, b, "SafeMath: division by zero"); } function DIV750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function ISCONTRACT755(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER74(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFER57.selector, to, value)); } function SAFETRANSFERFROM551(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFERFROM951.selector, from, to, value)); } function SAFEAPPROVE429(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE343(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.APPROVE196.selector, spender, value)); } function CALLOPTIONALRETURN536(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT755(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract YFIG is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("yfipaprika.finance", "YFIG", 18) { governance = tx.origin; } function MINT662(address account, uint256 amount) public { //inject NONSTANDARD NAMING require(TOTALSUPPLY886() + amount <= MAXSUPPLY198(), "Supply Max Reached"); require(minters[msg.sender], "!minter"); _MINT845(account, amount); } function BURN585(uint256 amount) external { //inject NONSTANDARD NAMING require(amount != 0, "you cannot burn zero amount"); _BURN745(msg.sender, amount); } function SETGOVERNANCE8(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER497(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER463(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
function MUL593(uint a, uint b) internal pure returns (uint) {
7,321,040
[ 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, 490, 1506, 6162, 23, 12, 11890, 279, 16, 2254, 324, 13, 2713, 16618, 1135, 261, 11890, 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, -100 ]
./full_match/421613/0x712A3480705560bB3158c8933403B04564305158/sources/project_/contracts/tokens/Corn.sol
* @dev There must be a farm on this LAND to execute this function/
modifier requireFarm(address farmAddress, bool requiredState) { if (requiredState) { require( ownerOfFarm[farmAddress].amount != 0, "You need to allocate land to grow crops on your farm" ); require( ownerOfFarm[farmAddress].amount == 0, "Ensure you release your land first" ); } } event Allocated(address sender, uint256 blockNumber, address farmAddress, uint256 amount, uint256 burnedAmountIncrease); event Released(address sender, uint256 amount, uint256 burnedAmountDecrease); event Composted(address sender, address farmAddress, uint256 amount, uint256 bonus); event Harvested(address sender, uint256 blockNumber, address farmAddress, address targetAddress, uint256 targetBlock, uint256 amount); event CollectibleEquipped(address sender, uint256 blockNumber, uint256 TokenID, CollectibleType collectibleType); event CollectibleReleased(address sender, uint256 blockNumber, uint256 TokenID, CollectibleType collectibleType);
11,566,782
[ 1, 9828, 1297, 506, 279, 284, 4610, 603, 333, 511, 4307, 358, 1836, 333, 445, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 2583, 42, 4610, 12, 2867, 284, 4610, 1887, 16, 1426, 1931, 1119, 13, 288, 203, 3639, 309, 261, 4718, 1119, 13, 288, 203, 5411, 2583, 12, 203, 7734, 3410, 951, 42, 4610, 63, 74, 4610, 1887, 8009, 8949, 480, 374, 16, 203, 7734, 315, 6225, 1608, 358, 10101, 19193, 358, 13334, 276, 16703, 603, 3433, 284, 4610, 6, 203, 5411, 11272, 203, 5411, 2583, 12, 203, 7734, 3410, 951, 42, 4610, 63, 74, 4610, 1887, 8009, 8949, 422, 374, 16, 203, 7734, 315, 12512, 1846, 3992, 3433, 19193, 1122, 6, 203, 5411, 11272, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 871, 12830, 690, 12, 2867, 5793, 16, 2254, 5034, 1203, 1854, 16, 1758, 284, 4610, 1887, 16, 2254, 5034, 3844, 16, 2254, 5034, 18305, 329, 6275, 382, 11908, 1769, 203, 565, 871, 10819, 72, 12, 2867, 5793, 16, 2254, 5034, 3844, 16, 2254, 5034, 18305, 329, 6275, 23326, 448, 1769, 203, 565, 871, 1286, 2767, 329, 12, 2867, 5793, 16, 1758, 284, 4610, 1887, 16, 2254, 5034, 3844, 16, 2254, 5034, 324, 22889, 1769, 203, 565, 871, 670, 297, 90, 3149, 12, 2867, 5793, 16, 2254, 5034, 1203, 1854, 16, 1758, 284, 4610, 1887, 16, 1758, 1018, 1887, 16, 2254, 5034, 1018, 1768, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 9302, 1523, 13142, 625, 1845, 12, 2867, 5793, 16, 2254, 5034, 1203, 1854, 16, 2254, 5034, 3155, 734, 16, 9302, 1523, 559, 3274, 1523, 559, 1769, 203, 565, 871, 9302, 1523, 26363, 12, 2867, 5793, 16, 2254, 5034, 1203, 2 ]
pragma solidity ^0.5.11; // Public-Sale for #3277-12000 stage of Voken2.0 // // More info: // https://vision.network // https://voken.io // // Contact us: // [email protected] // [email protected] /** * @dev Uint256 wrappers over Solidity's arithmetic operations with added overflow checks. */ library SafeMath256 { /** * @dev Returns the addition of two unsigned integers, reverting on 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). */ 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). */ 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. */ 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. Reverts on * division by zero. The result is rounded towards 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. */ 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Uint16 wrappers over Solidity's arithmetic operations with added overflow checks. */ library SafeMath16 { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 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). */ function sub(uint16 a, uint16 b) internal pure returns (uint16) { 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). */ function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b <= a, errorMessage); uint16 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. */ function mul(uint16 a, uint16 b) internal pure returns (uint16) { if (a == 0) { return 0; } uint16 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. */ function div(uint16 a, uint16 b) internal pure returns (uint16) { 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. */ function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. */ function mod(uint16 a, uint16 b) internal pure returns (uint16) { 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. */ function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b != 0, errorMessage); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @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. */ contract Ownable { address internal _owner; address internal _newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event OwnershipAccepted(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the addresses of the current and new owner. */ function owner() public view returns (address currentOwner, address newOwner) { currentOwner = _owner; newOwner = _newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(msg.sender), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner(address account) public view returns (bool) { return account == _owner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * IMPORTANT: Need to run {acceptOwnership} by the new owner. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _newOwner = newOwner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Accept ownership of the contract. * * Can only be called by the new owner. */ function acceptOwnership() public { require(msg.sender == _newOwner, "Ownable: caller is not the new owner address"); require(msg.sender != address(0), "Ownable: caller is the zero address"); emit OwnershipAccepted(_owner, msg.sender); _owner = msg.sender; _newOwner = address(0); } /** * @dev Rescue compatible ERC20 Token * * Can only be called by the current owner. */ function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(recipient != address(0), "Rescue: recipient is the zero address"); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount, "Rescue: amount exceeds balance"); _token.transfer(recipient, amount); } /** * @dev Withdraw Ether * * Can only be called by the current owner. */ function withdrawEther(address payable recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Withdraw: recipient is the zero address"); uint256 balance = address(this).balance; require(balance >= amount, "Withdraw: amount exceeds balance"); recipient.transfer(amount); } } /** * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { bool private _paused; event Paused(address account); event Unpaused(address account); /** * @dev Constructor */ constructor () internal { _paused = false; } /** * @return Returns true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Paused"); _; } /** * @dev Sets paused state. * * Can only be called by the current owner. */ function setPaused(bool value) external onlyOwner { _paused = value; if (_paused) { emit Paused(msg.sender); } else { emit Unpaused(msg.sender); } } } /** * @dev Part of ERC20 interface. */ interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } /** * @title Voken2.0 interface. */ interface IVoken2 { function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool); function whitelisted(address account) external view returns (bool); function whitelistReferee(address account) external view returns (address payable); function whitelistReferralsCount(address account) external view returns (uint256); } /** * @dev Interface of an allocation contract */ interface IAllocation { function reservedOf(address account) external view returns (uint256); } /** * @dev Allocation for VOKEN */ library Allocations { struct Allocation { uint256 amount; uint256 timestamp; } } /** * @title VokenShareholders interface. */ interface VokenShareholders { // } /** * @title Voken Public Sale v2.0 */ contract VokenPublicSale2 is Ownable, Pausable, IAllocation { using SafeMath16 for uint16; using SafeMath256 for uint256; using Roles for Roles.Role; using Allocations for Allocations.Allocation; // Proxy Roles.Role private _proxies; // Addresses IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB); VokenShareholders private _SHAREHOLDERS = VokenShareholders(0x7712F76D2A52141D44461CDbC8b660506DCAB752); address payable private _TEAM; // Referral rewards, 35% for 15 levels uint16[15] private REWARDS_PCT = [6, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]; // Limit uint16[] private LIMIT_COUNTER = [1, 3, 10, 50, 100, 200, 300]; uint256[] private LIMIT_WEIS = [100 ether, 50 ether, 40 ether, 30 ether, 20 ether, 10 ether, 5 ether]; uint256 private LIMIT_WEI_MIN = 3 ether; // 6,000 000 gas mininum uint24 private GAS_MIN = 6000000; // Price uint256 private VOKEN_USD_PRICE_START = 1000; // $ 0.00100 USD uint256 private VOKEN_USD_PRICE_STEP = 10; // $ + 0.00001 USD uint256 private STAGE_USD_CAP_START = 100000000; // $ 100 USD uint256 private STAGE_USD_CAP_STEP = 1000000; // $ +1 USD uint256 private STAGE_USD_CAP_MAX = 15100000000; // $ 15,100 USD // 1 Ether|Voken = xx.xxxxxx USD, with 6 decimals uint256 private _etherUsdPrice; uint256 private _vokenUsdPrice; // Progress uint16 private SEASON_MAX = 100; // 100 seasons max uint16 private SEASON_LIMIT = 20; // 20 season total uint16 private SEASON_STAGES = 600; // each 600 stages is a season uint16 private STAGE_MAX = SEASON_STAGES.mul(SEASON_MAX); uint16 private STAGE_LIMIT = SEASON_STAGES.mul(SEASON_LIMIT); uint16 private _stage; uint16 private _season; // Sum uint256 private _txs; uint256 private _vokenIssued; uint256 private _vokenIssuedTxs; uint256 private _vokenBonus; uint256 private _vokenBonusTxs; uint256 private _weiSold; uint256 private _weiRewarded; uint256 private _weiShareholders; uint256 private _weiTeam; uint256 private _weiPended; uint256 private _usdSold; uint256 private _usdRewarded; // Shareholders ratio uint256 private SHAREHOLDERS_RATIO_START = 15000000; // 15%, with 8 decimals uint256 private SHAREHOLDERS_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals uint256 private _shareholdersRatio; // Cache bool private _cacheWhitelisted; uint256 private _cacheWeiShareholders; uint256 private _cachePended; uint16[] private _cacheRewards; address payable[] private _cacheReferees; // Allocations mapping (address => Allocations.Allocation[]) private _allocations; // Account mapping (address => uint256) private _accountVokenIssued; mapping (address => uint256) private _accountVokenBonus; mapping (address => uint256) private _accountVokenReferral; mapping (address => uint256) private _accountVokenReferrals; mapping (address => uint256) private _accountUsdPurchased; mapping (address => uint256) private _accountWeiPurchased; mapping (address => uint256) private _accountUsdRewarded; mapping (address => uint256) private _accountWeiRewarded; // Stage mapping (uint16 => uint256) private _stageUsdSold; mapping (uint16 => uint256) private _stageVokenIssued; mapping (uint16 => uint256) private _stageVokenBonus; // Season mapping (uint16 => uint256) private _seasonWeiSold; mapping (uint16 => uint256) private _seasonWeiRewarded; mapping (uint16 => uint256) private _seasonWeiShareholders; mapping (uint16 => uint256) private _seasonWeiPended; mapping (uint16 => uint256) private _seasonUsdSold; mapping (uint16 => uint256) private _seasonUsdRewarded; mapping (uint16 => uint256) private _seasonUsdShareholders; mapping (uint16 => uint256) private _seasonVokenIssued; mapping (uint16 => uint256) private _seasonVokenBonus; // Account in season mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountIssued; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountBonus; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferral; mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountRewarded; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountReferrals; mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRewarded; // Season wei limit accounts mapping (uint16 => mapping (uint256 => address[])) private _seasonLimitAccounts; mapping (uint16 => address[]) private _seasonLimitWeiMinAccounts; // Referrals mapping (uint16 => address[]) private _seasonAccounts; mapping (uint16 => address[]) private _seasonReferrals; mapping (uint16 => mapping (address => bool)) private _seasonHasAccount; mapping (uint16 => mapping (address => bool)) private _seasonHasReferral; mapping (uint16 => mapping (address => address[])) private _seasonAccountReferrals; mapping (uint16 => mapping (address => mapping (address => bool))) private _seasonAccountHasReferral; // Events event ProxyAdded(address indexed account); event ProxyRemoved(address indexed account); event StageClosed(uint256 _stageNumber); event SeasonClosed(uint16 _seasonNumber); event AuditEtherPriceUpdated(uint256 value, address indexed account); event Log(uint256 value); /** * @dev Throws if called by account which is not a proxy. */ modifier onlyProxy() { require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role"); _; } /** * @dev Returns true if the `account` has the Proxy role. */ function isProxy(address account) public view returns (bool) { return _proxies.has(account); } /** * @dev Give an `account` access to the Proxy role. * * Can only be called by the current owner. */ function addProxy(address account) public onlyOwner { _proxies.add(account); emit ProxyAdded(account); } /** * @dev Remove an `account` access from the Proxy role. * * Can only be called by the current owner. */ function removeProxy(address account) public onlyOwner { _proxies.remove(account); emit ProxyRemoved(account); } /** * @dev Returns the VOKEN address. */ function VOKEN() public view returns (IVoken2) { return _VOKEN; } /** * @dev Returns the shareholders contract address. */ function SHAREHOLDERS() public view returns (VokenShareholders) { return _SHAREHOLDERS; } /** * @dev Returns the team wallet address. */ function TEAM() public view returns (address) { return _TEAM; } /** * @dev Returns the main status. */ function status() public view returns (uint16 stage, uint16 season, uint256 etherUsdPrice, uint256 vokenUsdPrice, uint256 shareholdersRatio) { if (_stage > STAGE_MAX) { stage = STAGE_MAX; season = SEASON_MAX; } else { stage = _stage; season = _season; } etherUsdPrice = _etherUsdPrice; vokenUsdPrice = _vokenUsdPrice; shareholdersRatio = _shareholdersRatio; } /** * @dev Returns the sum. */ function sum() public view returns(uint256 vokenIssued, uint256 vokenBonus, uint256 weiSold, uint256 weiRewarded, uint256 weiShareholders, uint256 weiTeam, uint256 weiPended, uint256 usdSold, uint256 usdRewarded) { vokenIssued = _vokenIssued; vokenBonus = _vokenBonus; weiSold = _weiSold; weiRewarded = _weiRewarded; weiShareholders = _weiShareholders; weiTeam = _weiTeam; weiPended = _weiPended; usdSold = _usdSold; usdRewarded = _usdRewarded; } /** * @dev Returns the transactions' counter. */ function transactions() public view returns(uint256 txs, uint256 vokenIssuedTxs, uint256 vokenBonusTxs) { txs = _txs; vokenIssuedTxs = _vokenIssuedTxs; vokenBonusTxs = _vokenBonusTxs; } /** * @dev Returns the `account` data. */ function queryAccount(address account) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenReferral, uint256 vokenReferrals, uint256 weiPurchased, uint256 weiRewarded, uint256 usdPurchased, uint256 usdRewarded) { vokenIssued = _accountVokenIssued[account]; vokenBonus = _accountVokenBonus[account]; vokenReferral = _accountVokenReferral[account]; vokenReferrals = _accountVokenReferrals[account]; weiPurchased = _accountWeiPurchased[account]; weiRewarded = _accountWeiRewarded[account]; usdPurchased = _accountUsdPurchased[account]; usdRewarded = _accountUsdRewarded[account]; } /** * @dev Returns the stage data by `stageIndex`. */ function stage(uint16 stageIndex) public view returns (uint256 vokenUsdPrice, uint256 shareholdersRatio, uint256 vokenIssued, uint256 vokenBonus, uint256 vokenCap, uint256 vokenOnSale, uint256 usdSold, uint256 usdCap, uint256 usdOnSale) { if (stageIndex <= STAGE_LIMIT) { vokenUsdPrice = _calcVokenUsdPrice(stageIndex); shareholdersRatio = _calcShareholdersRatio(stageIndex); vokenIssued = _stageVokenIssued[stageIndex]; vokenBonus = _stageVokenBonus[stageIndex]; vokenCap = _stageVokenCap(stageIndex); vokenOnSale = vokenCap.sub(vokenIssued); usdSold = _stageUsdSold[stageIndex]; usdCap = _stageUsdCap(stageIndex); usdOnSale = usdCap.sub(usdSold); } } /** * @dev Returns the season data by `seasonNumber`. */ function season(uint16 seasonNumber) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 weiSold, uint256 weiRewarded, uint256 weiShareholders, uint256 weiPended, uint256 usdSold, uint256 usdRewarded, uint256 usdShareholders) { if (seasonNumber <= SEASON_LIMIT) { vokenIssued = _seasonVokenIssued[seasonNumber]; vokenBonus = _seasonVokenBonus[seasonNumber]; weiSold = _seasonWeiSold[seasonNumber]; weiRewarded = _seasonWeiRewarded[seasonNumber]; weiShareholders = _seasonWeiShareholders[seasonNumber]; weiPended = _seasonWeiPended[seasonNumber]; usdSold = _seasonUsdSold[seasonNumber]; usdRewarded = _seasonUsdRewarded[seasonNumber]; usdShareholders = _seasonUsdShareholders[seasonNumber]; } } /** * @dev Returns the `account` data of #`seasonNumber` season. */ function accountInSeason(address account, uint16 seasonNumber) public view returns (uint256 vokenIssued, uint256 vokenBonus, uint256 vokenReferral, uint256 vokenReferrals, uint256 weiPurchased, uint256 weiReferrals, uint256 weiRewarded, uint256 usdPurchased, uint256 usdReferrals, uint256 usdRewarded) { if (seasonNumber > 0 && seasonNumber <= SEASON_LIMIT) { vokenIssued = _vokenSeasonAccountIssued[seasonNumber][account]; vokenBonus = _vokenSeasonAccountBonus[seasonNumber][account]; vokenReferral = _vokenSeasonAccountReferral[seasonNumber][account]; vokenReferrals = _vokenSeasonAccountReferrals[seasonNumber][account]; weiPurchased = _weiSeasonAccountPurchased[seasonNumber][account]; weiReferrals = _weiSeasonAccountReferrals[seasonNumber][account]; weiRewarded = _weiSeasonAccountRewarded[seasonNumber][account]; usdPurchased = _usdSeasonAccountPurchased[seasonNumber][account]; usdReferrals = _usdSeasonAccountReferrals[seasonNumber][account]; usdRewarded = _usdSeasonAccountRewarded[seasonNumber][account]; } } /** * @dev Referral accounts in a season by `seasonNumber`. */ function seasonReferrals(uint16 seasonNumber) public view returns (address[] memory) { return _seasonReferrals[seasonNumber]; } /** * @dev Referral accounts in a season by `seasonNumber` of `account`. */ function seasonAccountReferrals(uint16 seasonNumber, address account) public view returns (address[] memory) { return _seasonAccountReferrals[seasonNumber][account]; } /** * @dev Voken price in USD, by `stageIndex`. */ function _calcVokenUsdPrice(uint16 stageIndex) private view returns (uint256) { return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex)); } /** * @dev Returns the shareholders ratio by `stageIndex`. */ function _calcShareholdersRatio(uint16 stageIndex) private view returns (uint256) { return SHAREHOLDERS_RATIO_START.add(SHAREHOLDERS_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX)); } /** * @dev Returns the dollor cap of `stageIndex`. */ function _stageUsdCap(uint16 stageIndex) private view returns (uint256) { uint256 __usdCap = STAGE_USD_CAP_START.add(STAGE_USD_CAP_STEP.mul(stageIndex)); if (__usdCap > STAGE_USD_CAP_MAX) { return STAGE_USD_CAP_MAX; } return __usdCap; } /** * @dev Returns the Voken cap of `stageIndex`. */ function _stageVokenCap(uint16 stageIndex) private view returns (uint256) { return _stageUsdCap(stageIndex).mul(1000000).div(_calcVokenUsdPrice(stageIndex)); } /** * @dev Returns an {uint256} by `value` * _shareholdersRatio / 100000000 */ function _2shareholders(uint256 value) private view returns (uint256) { return value.mul(_shareholdersRatio).div(100000000); } /** * @dev wei => USD, by `weiAmount`. */ function _wei2usd(uint256 weiAmount) private view returns (uint256) { return weiAmount.mul(_etherUsdPrice).div(1 ether); } /** * @dev USD => wei, by `usdAmount`. */ function _usd2wei(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1 ether).div(_etherUsdPrice); } /** * @dev USD => voken, by `usdAmount`. */ function _usd2voken(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1000000).div(_vokenUsdPrice); } /** * @dev Returns the season number by `stageIndex`. */ function _seasonNumber(uint16 stageIndex) private view returns (uint16) { if (stageIndex > 0) { uint16 __seasonNumber = stageIndex.div(SEASON_STAGES); if (stageIndex.mod(SEASON_STAGES) > 0) { return __seasonNumber.add(1); } return __seasonNumber; } return 1; } /** * Close the current stage. */ function _closeStage() private { _stage = _stage.add(1); emit StageClosed(_stage); // Close current season uint16 __seasonNumber = _seasonNumber(_stage); if (_season < __seasonNumber) { _season = __seasonNumber; emit SeasonClosed(_season); } _vokenUsdPrice = _calcVokenUsdPrice(_stage); _shareholdersRatio = _calcShareholdersRatio(_stage); } /** * @dev Update audit ether price. */ function updateEtherUsdPrice(uint256 value) external onlyProxy { _etherUsdPrice = value; emit AuditEtherPriceUpdated(value, msg.sender); } /** * @dev Update team wallet address. */ function updateTeamWallet(address payable account) external onlyOwner { _TEAM = account; } /** * @dev Returns current max wei value. */ function weiMax() public view returns (uint256) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (_seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return LIMIT_WEIS[i]; } } return LIMIT_WEI_MIN; } /** * @dev Returns the {limitIndex} and {weiMax}. */ function _limit(uint256 weiAmount) private view returns (uint256 __wei) { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { return 0; } if (__purchased < LIMIT_WEIS[i]) { __wei = LIMIT_WEIS[i].sub(__purchased); if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) { return __wei; } } } if (__purchased < LIMIT_WEI_MIN) { return LIMIT_WEI_MIN.sub(__purchased); } } /** * @dev Updates the season limit accounts, or wei min accounts. */ function _updateSeasonLimits() private { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; if (__purchased > LIMIT_WEI_MIN) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { _seasonLimitAccounts[_season][i].push(msg.sender); return; } } } else if (__purchased == LIMIT_WEI_MIN) { _seasonLimitWeiMinAccounts[_season].push(msg.sender); return; } } /** * @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`. */ function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) { if (limitIndex < LIMIT_WEIS.length) { weis = LIMIT_WEIS[limitIndex]; accounts = _seasonLimitAccounts[seasonNumber][limitIndex]; } else { weis = LIMIT_WEI_MIN; accounts = _seasonLimitWeiMinAccounts[seasonNumber]; } } /** * @dev constructor */ constructor () public { _stage = 3277; _season = _seasonNumber(_stage); _vokenUsdPrice = _calcVokenUsdPrice(_stage); _shareholdersRatio = _calcShareholdersRatio(_stage); _TEAM = msg.sender; addProxy(msg.sender); } /** * @dev Receive ETH, and excute the exchange. */ function () external payable whenNotPaused { require(_etherUsdPrice > 0, "VokenPublicSale2: Audit ETH price is zero"); require(_stage <= STAGE_MAX, "VokenPublicSale2: Voken Public-Sale Completled"); uint256 __usdAmount; uint256 __usdRemain; uint256 __usdUsed; uint256 __weiUsed; uint256 __voken; // Limit uint256 __weiMax = _limit(msg.value); if (__weiMax < msg.value) { __usdAmount = _wei2usd(__weiMax); } else { __usdAmount = _wei2usd(msg.value); } __usdRemain = __usdAmount; if (__usdRemain > 0) { // cache _cache(); // USD => Voken while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = _tx(__usdRemain); __voken = __voken.add(__txVokenIssued); } // Used __usdUsed = __usdAmount.sub(__usdRemain); __weiUsed = _usd2wei(__usdUsed); // Whitelist if (_cacheWhitelisted && __voken > 0) { _mintVokenBonus(__voken); for(uint16 i = 0; i < _cacheReferees.length; i++) { address payable __referee = _cacheReferees[i]; uint256 __usdReward = __usdUsed.mul(_cacheRewards[i]).div(100); uint256 __weiReward = __weiUsed.mul(_cacheRewards[i]).div(100); __referee.transfer(__weiReward); _usdRewarded = _usdRewarded.add(__usdReward); _weiRewarded = _weiRewarded.add(__weiReward); _accountUsdRewarded[__referee] = _accountUsdRewarded[__referee].add(__usdReward); _accountWeiRewarded[__referee] = _accountWeiRewarded[__referee].add(__weiReward); } if (_cachePended > 0) { _weiPended = _weiPended.add(__weiUsed.mul(_cachePended).div(100)); } } // Counter if (__weiUsed > 0) { _txs = _txs.add(1); _usdSold = _usdSold.add(__usdUsed); _weiSold = _weiSold.add(__weiUsed); _accountUsdPurchased[msg.sender] = _accountUsdPurchased[msg.sender].add(__usdUsed); _accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed); // Wei for SHAREHOLDERS _weiShareholders = _weiShareholders.add(_cacheWeiShareholders); (bool __bool,) = address(_SHAREHOLDERS).call.value(_cacheWeiShareholders)(""); assert(__bool); // Wei for TEAM uint256 __weiTeam = _weiSold.sub(_weiRewarded).sub(_weiShareholders).sub(_weiPended).sub(_weiTeam); _weiTeam = _weiTeam.add(__weiTeam); _TEAM.transfer(__weiTeam); // Update season limits _updateSeasonLimits(); } // Reset cache _resetCache(); } // If wei remains, refund. uint256 __weiRemain = msg.value.sub(__weiUsed); if (__weiRemain > 0) { msg.sender.transfer(__weiRemain); } } /** * @dev Cache. */ function _cache() private { if (!_seasonHasAccount[_season][msg.sender]) { _seasonAccounts[_season].push(msg.sender); _seasonHasAccount[_season][msg.sender] = true; } _cacheWhitelisted = _VOKEN.whitelisted(msg.sender); if (_cacheWhitelisted) { address __account = msg.sender; for(uint16 i = 0; i < REWARDS_PCT.length; i++) { address __referee = _VOKEN.whitelistReferee(__account); if (__referee != address(0) && __referee != __account && _VOKEN.whitelistReferralsCount(__referee) > i) { if (!_seasonHasReferral[_season][__referee]) { _seasonReferrals[_season].push(__referee); _seasonHasReferral[_season][__referee] = true; } if (!_seasonAccountHasReferral[_season][__referee][__account]) { _seasonAccountReferrals[_season][__referee].push(__account); _seasonAccountHasReferral[_season][__referee][__account] = true; } _cacheReferees.push(address(uint160(__referee))); _cacheRewards.push(REWARDS_PCT[i]); } else { _cachePended = _cachePended.add(REWARDS_PCT[i]); } __account = __referee; } } } /** * @dev Reset cache. */ function _resetCache() private { delete _cacheWeiShareholders; if (_cacheWhitelisted) { delete _cacheWhitelisted; delete _cacheReferees; delete _cacheRewards; delete _cachePended; } } /** * @dev USD => Voken */ function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) { uint256 __stageUsdCap = _stageUsdCap(_stage); uint256 __usdUsed; // in stage if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) { __usdUsed = __usd; (__voken, ) = _calcExchange(__usdUsed); _mintVokenIssued(__voken); // close stage, if stage dollor cap reached if (__stageUsdCap == _stageUsdSold[_stage]) { _closeStage(); } } // close stage else { __usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]); (__voken, ) = _calcExchange(__usdUsed); _mintVokenIssued(__voken); _closeStage(); __usdRemain = __usd.sub(__usdUsed); } } /** * @dev USD => voken & wei, and make records. */ function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) { __wei = _usd2wei(__usd); __voken = _usd2voken(__usd); uint256 __usdShareholders = _2shareholders(__usd); uint256 __weiShareholders = _usd2wei(__usdShareholders); // Stage: usd _stageUsdSold[_stage] = _stageUsdSold[_stage].add(__usd); // Season: usd, wei _seasonUsdSold[_season] = _seasonUsdSold[_season].add(__usd); _seasonWeiSold[_season] = _seasonWeiSold[_season].add(__wei); // Season: wei pended if (_cachePended > 0) { _seasonWeiPended[_season] = _seasonWeiPended[_season].add(__wei.mul(_cachePended).div(100)); } // Season shareholders: usd, wei _seasonUsdShareholders[_season] = _seasonUsdShareholders[_season].add(__usdShareholders); _seasonWeiShareholders[_season] = _seasonWeiShareholders[_season].add(__weiShareholders); // Cache _cacheWeiShareholders = _cacheWeiShareholders.add(__weiShareholders); // Season => account: usd, wei _usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(__usd); _weiSeasonAccountPurchased[_season][msg.sender] = _weiSeasonAccountPurchased[_season][msg.sender].add(__wei); // season referral account if (_cacheWhitelisted) { for (uint16 i = 0; i < _cacheRewards.length; i++) { address __referee = _cacheReferees[i]; uint256 __usdReward = __usd.mul(_cacheRewards[i]).div(100); uint256 __weiReward = __wei.mul(_cacheRewards[i]).div(100); // season _seasonUsdRewarded[_season] = _seasonUsdRewarded[_season].add(__usdReward); _seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward); // season => account _usdSeasonAccountRewarded[_season][__referee] = _usdSeasonAccountRewarded[_season][__referee].add(__usdReward); _weiSeasonAccountRewarded[_season][__referee] = _weiSeasonAccountRewarded[_season][__referee].add(__weiReward); _usdSeasonAccountReferrals[_season][__referee] = _usdSeasonAccountReferrals[_season][__referee].add(__usd); _weiSeasonAccountReferrals[_season][__referee] = _weiSeasonAccountReferrals[_season][__referee].add(__wei); _vokenSeasonAccountReferrals[_season][__referee] = _vokenSeasonAccountReferrals[_season][__referee].add(__voken); _accountVokenReferrals[__referee] = _accountVokenReferrals[__referee].add(__voken); if (i == 0) { _vokenSeasonAccountReferral[_season][__referee] = _vokenSeasonAccountReferral[_season][__referee].add(__voken); _accountVokenReferral[__referee] = _accountVokenReferral[__referee].add(__voken); } } } } /** * @dev Mint Voken issued. */ function _mintVokenIssued(uint256 amount) private { // Global _vokenIssued = _vokenIssued.add(amount); _vokenIssuedTxs = _vokenIssuedTxs.add(1); // Account _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount); // Stage _stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount); // Season _seasonVokenIssued[_season] = _seasonVokenIssued[_season].add(amount); _vokenSeasonAccountIssued[_season][msg.sender] = _vokenSeasonAccountIssued[_season][msg.sender].add(amount); // Mint assert(_VOKEN.mint(msg.sender, amount)); } /** * @dev Mint Voken bonus. */ function _mintVokenBonus(uint256 amount) private { // Global _vokenBonus = _vokenBonus.add(amount); _vokenBonusTxs = _vokenBonusTxs.add(1); // Account _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount); // Stage _stageVokenBonus[_stage] = _stageVokenBonus[_stage].add(amount); // Season _seasonVokenBonus[_season] = _seasonVokenBonus[_season].add(amount); _vokenSeasonAccountBonus[_season][msg.sender] = _vokenSeasonAccountBonus[_season][msg.sender].add(amount); // Mint with allocation Allocations.Allocation memory __allocation; __allocation.amount = amount; __allocation.timestamp = now; _allocations[msg.sender].push(__allocation); assert(_VOKEN.mintWithAllocation(msg.sender, amount, address(this))); } /** * @dev Returns the reserved amount of VOKEN by `account`. */ function reservedOf(address account) public view returns (uint256) { Allocations.Allocation[] memory __allocations = _allocations[account]; uint256 __len = __allocations.length; if (__len > 0) { uint256 __vokenIssued = _accountVokenIssued[account]; uint256 __vokenBonus = _accountVokenBonus[account]; uint256 __vokenReferral = _accountVokenReferral[account]; uint256 __vokenBalance = _VOKEN.balanceOf(account); // balance fixed, by Voken issued. if (__vokenIssued < __vokenBalance) { __vokenBalance = __vokenBalance.sub(__vokenIssued); } else { __vokenBalance = 0; } // balance fixed, by Voken bonus. if (__vokenBonus < __vokenBalance) { __vokenBalance = __vokenBalance.sub(__vokenBonus); } else { __vokenBalance = 0; } uint256 __reserved; for (uint256 i = 0; i < __len; i++) { // Voken reserved. Allocations.Allocation memory __allocation = __allocations[i]; __reserved = __reserved.add(__allocation.amount); if (now >= __allocation.timestamp.add(90 days)) { // default: 180 days. uint256 __distance = 180 days; // shorten the distance, by Voken referral, at least 120 days. if (__vokenReferral > __allocation.amount) { __distance = __distance.sub(__vokenReferral.div(__allocation.amount).mul(1 days)); if (__distance > 120 days) { __distance = 120 days; } } // shorten the distance, by Voken holding if (__vokenBalance > __allocation.amount) { __distance = __distance.sub(__vokenBalance.div(__allocation.amount).mul(30 days)); } // at least: 90 days if (__distance > 90 days) { __distance = 90 days; } // calc reserved uint256 __timestamp = __allocation.timestamp.add(__distance); if (now > __timestamp) { uint256 __passed = now.sub(__timestamp).div(1 days).add(1); if (__passed > 30) { __reserved = __reserved.sub(__allocation.amount); } else { __reserved = __reserved.sub(__allocation.amount.mul(__passed).div(30)); } } } } return __reserved; } return 0; } }
* @dev USD => wei, by `usdAmount`./
function _usd2wei(uint256 usdAmount) private view returns (uint256) { return usdAmount.mul(1 ether).div(_etherUsdPrice); }
14,101,998
[ 1, 3378, 40, 516, 732, 77, 16, 635, 1375, 407, 72, 6275, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 407, 72, 22, 1814, 77, 12, 11890, 5034, 584, 72, 6275, 13, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 584, 72, 6275, 18, 16411, 12, 21, 225, 2437, 2934, 2892, 24899, 2437, 3477, 72, 5147, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x21499643B1Dd73168807eb1eDfa0b43b50b8F30F/sources/cache/solpp-generated-contracts/StakingV1.sol
@inheritdoc IStakingV1
function unstake(uint256 _amount, uint256 _unstakingPeriod) external whenNotPaused { _unstake(_msgSender(), _amount, _unstakingPeriod); }
4,624,959
[ 1, 36, 10093, 467, 510, 6159, 58, 21, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 334, 911, 12, 11890, 5034, 389, 8949, 16, 2254, 5034, 389, 23412, 6159, 5027, 13, 203, 3639, 3903, 203, 3639, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 389, 23412, 911, 24899, 3576, 12021, 9334, 389, 8949, 16, 389, 23412, 6159, 5027, 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 ]
./full_match/42/0x988b262D8E905ef23fdaBd4bf8236DB79656D469/sources/MasterChef.sol
return user.amount.mul(accYfcentralPerShare).div(1e12).sub(user.rewardDebt);
return user.amount.mul(userrewardPerShare).div(1e18).sub(user.rewardDebt);
9,594,263
[ 1, 2463, 729, 18, 8949, 18, 16411, 12, 8981, 61, 7142, 12839, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 327, 729, 18, 8949, 18, 16411, 12, 1355, 266, 2913, 2173, 9535, 2934, 2892, 12, 21, 73, 2643, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 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 ]
./partial_match/1/0x93C5cF832AD6Be0a7BF5d70B05FBc50864982B46/sources/src/types.sol
@notice The data stored for each indexed strategy.
struct IndexedStrategy { uint8 index; bytes params; }
3,942,555
[ 1, 1986, 501, 4041, 364, 1517, 8808, 6252, 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, 1697, 22524, 4525, 288, 203, 565, 2254, 28, 770, 31, 203, 565, 1731, 859, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: CC0-1.0 pragma solidity ^0.8.0; // constants import "./LSP7Constants.sol"; import "../LSP1UniversalReceiver/LSP1Constants.sol"; import "../LSP4DigitalAssetMetadata/LSP4Constants.sol"; // interfaces import "../LSP1UniversalReceiver/ILSP1UniversalReceiver.sol"; import "./ILSP7DigitalAsset.sol"; // modules import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@erc725/smart-contracts/contracts/ERC725Y.sol"; // library import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; /** * @title LSP7DigitalAsset contract * @author Matthew Stevens * @dev Core Implementation of a LSP7 compliant contract. */ abstract contract LSP7DigitalAssetCore is Context, ILSP7DigitalAsset { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; using Address for address; // --- Storage bool internal _isNFT; uint256 internal _existingTokens; // Mapping from `tokenOwner` to an `amount` of tokens mapping(address => uint256) internal _tokenOwnerBalances; // Mapping a `tokenOwner` to an `operator` to `amount` of tokens. mapping(address => mapping(address => uint256)) internal _operatorAuthorizedAmount; // --- Token queries /** * @inheritdoc ILSP7DigitalAsset */ function decimals() public view override returns (uint256) { return _isNFT ? 0 : 18; } /** * @inheritdoc ILSP7DigitalAsset */ function totalSupply() public view override returns (uint256) { return _existingTokens; } // --- Token owner queries /** * @inheritdoc ILSP7DigitalAsset */ function balanceOf(address tokenOwner) public view override returns (uint256) { return _tokenOwnerBalances[tokenOwner]; } // --- Operator functionality /** * @inheritdoc ILSP7DigitalAsset */ function authorizeOperator(address operator, uint256 amount) public virtual override { _updateOperator(_msgSender(), operator, amount); } /** * @inheritdoc ILSP7DigitalAsset */ function revokeOperator(address operator) public virtual override { _updateOperator(_msgSender(), operator, 0); } /** * @inheritdoc ILSP7DigitalAsset */ function isOperatorFor(address operator, address tokenOwner) public view virtual override returns (uint256) { if (tokenOwner == operator) { return _tokenOwnerBalances[tokenOwner]; } else { return _operatorAuthorizedAmount[tokenOwner][operator]; } } // --- Transfer functionality /** * @inheritdoc ILSP7DigitalAsset */ function transfer( address from, address to, uint256 amount, bool force, bytes memory data ) public virtual override { address operator = _msgSender(); if (operator != from) { uint256 operatorAmount = _operatorAuthorizedAmount[from][operator]; require( operatorAmount >= amount, "LSP7: transfer amount exceeds operator authorized amount" ); _updateOperator( from, operator, _operatorAuthorizedAmount[from][operator] - amount ); } _transfer(from, to, amount, force, data); } /** * @inheritdoc ILSP7DigitalAsset */ function transferBatch( address[] memory from, address[] memory to, uint256[] memory amount, bool force, bytes[] memory data ) external virtual override { require( from.length == to.length && from.length == amount.length && from.length == data.length, "LSP7: transferBatch list length mismatch" ); for (uint256 i = 0; i < from.length; i++) { // using the public transfer function to handle updates to operator authorized amounts transfer(from[i], to[i], amount[i], force, data[i]); } } /** * @dev Changes token `amount` the `operator` has access to from `tokenOwner` tokens. If the * amount is zero then the operator is being revoked, otherwise the operator amount is being * modified. * * See {isOperatorFor}. * * Emits either {AuthorizedOperator} or {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. * - `operator` cannot be the zero address. */ function _updateOperator( address tokenOwner, address operator, uint256 amount ) internal virtual { require( operator != tokenOwner, "LSP7: updating operator failed, can not use token owner as operator" ); require( operator != address(0), "LSP7: updating operator failed, operator can not be zero address" ); require( tokenOwner != address(0), "LSP7: updating operator failed, can not set operator for zero address" ); _operatorAuthorizedAmount[tokenOwner][operator] = amount; if (amount > 0) { emit AuthorizedOperator(operator, tokenOwner, amount); } else { emit RevokedOperator(operator, tokenOwner); } } /** * @dev Mints `amount` tokens and transfers it to `to`. * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint( address to, uint256 amount, bool force, bytes memory data ) internal virtual { require(to != address(0), "LSP7: mint to the zero address not allowed"); address operator = _msgSender(); _beforeTokenTransfer(address(0), to, amount); _tokenOwnerBalances[to] += amount; emit Transfer(operator, address(0), to, amount, force, data); _notifyTokenReceiver(address(0), to, amount, force, data); } /** * @dev Destroys `amount` tokens. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens. * - If the caller is not `from`, it must be an operator for `from` with access to at least * `amount` tokens. * * Emits a {Transfer} event. */ function _burn( address from, uint256 amount, bytes memory data ) internal virtual { require(from != address(0), "LSP7: burn from the zero address"); require( _tokenOwnerBalances[from] >= amount, "LSP7: burn amount exceeds tokenOwner balance" ); address operator = _msgSender(); if (operator != from) { require( _operatorAuthorizedAmount[from][operator] >= amount, "LSP7: burn amount exceeds operator authorized amount" ); _operatorAuthorizedAmount[from][operator] -= amount; } _notifyTokenSender(from, address(0), amount, data); _beforeTokenTransfer(from, address(0), amount); _tokenOwnerBalances[from] -= amount; emit Transfer(operator, from, address(0), amount, false, data); } /** * @dev Transfers `amount` tokens from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens. * - If the caller is not `from`, it must be an operator for `from` with access to at least * `amount` tokens. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 amount, bool force, bytes memory data ) internal virtual { require(from != address(0), "LSP7: transfer from the zero address"); require(to != address(0), "LSP7: transfer to the zero address"); require( _tokenOwnerBalances[from] >= amount, "LSP7: transfer amount exceeds tokenOwner balance" ); address operator = _msgSender(); _notifyTokenSender(from, to, amount, data); _beforeTokenTransfer(from, to, amount); _tokenOwnerBalances[from] -= amount; _tokenOwnerBalances[to] += amount; emit Transfer(operator, from, to, amount, force, data); _notifyTokenReceiver(from, to, amount, force, data); } /** * @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 `amount` tokens will be * transferred to `to`. * - When `from` is zero, `amount` tokens will be minted for `to`. * - When `to` is zero, ``from``'s `amount` tokens will be burned. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual { // tokens being minted if (from == address(0)) { _existingTokens += amount; } // tokens being burned if (to == address(0)) { _existingTokens -= amount; } } /** * @dev An attempt is made to notify the token sender about the `amount` tokens changing owners using * LSP1 interface. */ function _notifyTokenSender( address from, address to, uint256 amount, bytes memory data ) internal virtual { if ( ERC165Checker.supportsERC165(from) && ERC165Checker.supportsInterface(from, _INTERFACEID_LSP1) ) { bytes memory packedData = abi.encodePacked(from, to, amount, data); ILSP1UniversalReceiver(from).universalReceiver( _TYPEID_LSP7_TOKENSSENDER, packedData ); } } /** * @dev An attempt is made to notify the token receiver about the `amount` tokens changing owners * using LSP1 interface. When force is FALSE the token receiver MUST support LSP1. * * The receiver may revert when the token being sent is not wanted. */ function _notifyTokenReceiver( address from, address to, uint256 amount, bool force, bytes memory data ) internal virtual { if ( ERC165Checker.supportsERC165(to) && ERC165Checker.supportsInterface(to, _INTERFACEID_LSP1) ) { bytes memory packedData = abi.encodePacked(from, to, amount, data); ILSP1UniversalReceiver(to).universalReceiver( _TYPEID_LSP7_TOKENSRECIPIENT, packedData ); } else if (!force) { if (to.isContract()) { revert("LSP7: token receiver contract missing LSP1 interface"); } else { revert("LSP7: token receiver is EOA"); } } } }
* @inheritdoc ILSP7DigitalAsset/
function balanceOf(address tokenOwner) public view override returns (uint256) { return _tokenOwnerBalances[tokenOwner]; }
12,759,738
[ 1, 36, 10093, 467, 3045, 52, 27, 4907, 7053, 6672, 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, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 2316, 5541, 38, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.9.3 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // SPDX: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); } // File @openzeppelin/contracts/interfaces/[email protected] // SPDX: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // File @openzeppelin/contracts/utils/math/[email protected] // SPDX: MIT // OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/access/[email protected] // SPDX: MIT // 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 @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 @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 @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 contracts/Revolver.sol /* * ΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä ΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä Γûä Γûä ΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä Γûä Γûä Γûä ΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä ΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä * ΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûî * ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûêΓûæΓûîΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûêΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûêΓûæΓûî * ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî * ΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûêΓûæΓûîΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä ΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûêΓûæΓûî * ΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûî * ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûêΓûæΓûêΓûÇΓûÇ ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÉΓûæΓûêΓûÇΓûÇΓûÇΓûÇΓûêΓûæΓûêΓûÇΓûÇ * ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûî * ΓûÉΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä ΓûÉΓûæΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûêΓûæΓûîΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûÉΓûæΓûÉΓûæΓûî ΓûÉΓûæΓûêΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûäΓûä ΓûÉΓûæΓûî ΓûÉΓûæΓûî * ΓûÉΓûæΓûî ΓûÉΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûî ΓûÉΓûæΓûî ΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûæΓûîΓûÉΓûæΓûî ΓûÉΓûæΓûî * ΓûÇ ΓûÇ ΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÇ ΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÇ ΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇΓûÇ ΓûÇ ΓûÇ * The year is 2050, and the new gold rush is only getting started. * In a landscape dried up of opportunities, where danger and subterfuge lies behind every corner, * where behind every venture hides a bandit waiting to take off with your bags, a new hope shines * for the new generation of gold-chasing gunslingers that, 200 years later, is rising up to the * challenge to chase the ultimate reward. * With the sandy plains of crypto becoming more dangerous and scarce with every passing day, * the REVOlver carrying gunslingers turned to each other, coming up with a plan to ensure a path * to greatness would keep existing: they would bet their riches with each other, money painstakingly * earned in the bygone golden days, in duels that only fellow REVOlvers could participate in. * Their riches might change hands, but theyΓÇÖd never be truly gone, always in reach to be regained * on another day...but that wasnΓÇÖt all. * Website: https://revolverevolution.dev * Telegram: https://t.me/revolverpreverify * * */ //SPDX: UNLICENSED pragma solidity ^0.8.4; // Seriously if you audit this and ping it for "no safemath used" you're gonna out yourself as an idiot // SafeMath is by default included in solidity 0.8, I've only included it for the transferFrom contract RevolverToken is Context, IERC20, Ownable { using SafeMath for uint256; // Constants string private constant _name = "Revolver"; string private constant _symbol = "REVO"; // 0, 1, 2 uint8 private constant _bl = 2; // Standard decimals uint8 private constant _decimals = 9; // 1 bil uint256 private constant _tTotal = 1000000000 * 10**9; // Mappings mapping(address => uint256) private tokensOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _bots; mapping(address => uint256) private _lastTxBlock; mapping(address => uint256) private botBlock; mapping(address => uint256) private botBalance; mapping(address => uint256) private airdropTokens; // Arrays address[] private airdropPrivateList; // Global variables // Block of 256 bits address payable private _feeAddrWallet1; // Storage for opening block uint32 private openBlock; // Tax controls - how much to swap - .1% by default uint32 private swapPerDivisor = 1000; // Excess gas that triggers a tax sell uint32 private taxGasThreshold = 300000; // Storage block closed // Block of 256 bits address payable private _feeAddrWallet2; // Tax distribution ratios uint32 private devRatio = 3000; uint32 private marketingRatio = 7000; bool private cooldownEnabled = false; bool private transferCooldownEnabled = false; // 16 bits remaining // Storage block closed // Block of 256 bits address private uniswapV2Pair; uint32 private buyTax = 10000; uint32 private sellTax = 10000; uint32 private transferTax = 0; // Storage block closed // Block of 256 bits address private _controller; uint32 private maxTxDivisor = 1; uint32 private maxWalletDivisor = 1; bool private isBot; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; // Storage block closed IUniswapV2Router02 private uniswapV2Router; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier taxHolderOnly() { require( _msgSender() == _feeAddrWallet1 || _msgSender() == _feeAddrWallet2 || _msgSender() == owner() ); _; } modifier onlyERC20Controller() { require( _controller == _msgSender(), "TokenClawback: caller is not the ERC20 controller." ); _; } modifier onlyDev() { require(_msgSender() == _feeAddrWallet2, "REVO: Only developer can set this."); _; } constructor() { // ERC20 controller _controller = payable(0x4bB21b91325c6E813Bc4e8f4d5878676aD96fb84); // Marketing _feeAddrWallet1 = payable(0xa302bd37C82a3780729c3b91732cd459A75200D6); // Developer _feeAddrWallet2 = payable(0x4bB21b91325c6E813Bc4e8f4d5878676aD96fb84); tokensOwned[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return abBalance(account); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /// @notice Sets cooldown status. Only callable by owner. /// @param onoff The boolean to set. function setCooldownEnabled(bool onoff) external onlyOwner { cooldownEnabled = onoff; } 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"); isBot = false; uint32 _taxAmt; if ( from != owner() && to != owner() && from != address(this) && !_isExcludedFromFee[to] && !_isExcludedFromFee[from] ) { require(!_bots[to] && !_bots[from], "No bots."); // Buys if (from == uniswapV2Pair && to != address(uniswapV2Router)) { _taxAmt = buyTax; if(cooldownEnabled) { // Check if last tx occurred this block - prevents sandwich attacks require(_lastTxBlock[to] != block.number, "REVO: One tx per block."); _lastTxBlock[to] = block.number; } // Set it now if(openBlock + _bl > block.number) { // Bot isBot = true; } else { checkTxMax(to, amount); } } else if (to == uniswapV2Pair && from != address(uniswapV2Router)) { // Sells // Check max tx - can't do elsewhere require(amount <= _tTotal/maxTxDivisor, "REVO: Over max transaction amount."); // Check if last tx occurred this block - prevents sandwich attacks if(cooldownEnabled) { require(_lastTxBlock[from] != block.number, "REVO: One tx per block."); _lastTxBlock[from] == block.number; } // Check for tax sells { uint256 contractTokenBalance = trueBalance(address(this)); bool canSwap = contractTokenBalance >= _tTotal/swapPerDivisor; if (swapEnabled && canSwap && !inSwap && taxGasCheck()) { uint32 oldTax = _taxAmt; doTaxes(_tTotal/swapPerDivisor); _taxAmt = oldTax; } } // Sells _taxAmt = sellTax; } else { _taxAmt = transferTax; } } else { // Only make it here if it's from or to owner or from contract address. _taxAmt = 0; } _tokenTransfer(from, to, amount, _taxAmt); } /// @notice Sets tax swap boolean. Only callable by owner. /// @param enabled If tax sell is enabled. function swapAndLiquifyEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } /// @notice Set the tax amount to swap per sell. Only callable by owner. /// @param divisor the divisor to set function setSwapPerSellAmount(uint32 divisor) external onlyOwner { swapPerDivisor = divisor; } function doTaxes(uint256 tokenAmount) private { inSwap = true; address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); sendETHToFee(address(this).balance); inSwap = false; } function sendETHToFee(uint256 amount) private { // This fixes gas reprice issues - reentrancy is not an issue as the fee wallets are trusted. uint32 divisor = marketingRatio + devRatio; // Marketing Address.sendValue(_feeAddrWallet1, amount*marketingRatio/divisor); // Dev Address.sendValue(_feeAddrWallet2, amount*devRatio/divisor); } /// @notice Sets new max tx amount. Only callable by owner. /// @param divisor The new amount to set, without 0's. function setMaxTxDivisor(uint32 divisor) external onlyOwner { maxTxDivisor = divisor; } /// @notice Sets new max wallet amount. Only callable by owner. /// @param divisor The new amount to set, without 0's. function setMaxWalletDivisor(uint32 divisor) external onlyOwner { maxWalletDivisor = divisor; } function checkTxMax(address to, uint256 amount) private view { // Not over max tx amount require(amount <= _tTotal/maxTxDivisor, "REVO: Over max transaction amount."); // Max wallet require( trueBalance(to) + amount <= _tTotal/maxWalletDivisor, "REVO: Over max wallet amount." ); } /// @notice Changes wallet 1 address. Only callable by owner. /// @param newWallet The address to set as wallet 1. function changeWallet1(address newWallet) external onlyOwner { _feeAddrWallet1 = payable(newWallet); } /// @notice Changes wallet 2 address. Only callable by the ERC20 controller. /// @param newWallet The address to set as wallet 2. function changeWallet2(address newWallet) external onlyERC20Controller { _feeAddrWallet2 = payable(newWallet); } /// @notice Changes ERC20 controller address. Only callable by dev. /// @param newWallet the address to set as the controller. function changeERC20Controller(address newWallet) external onlyDev { _controller = payable(newWallet); } /// @notice Starts trading. Only callable by owner. function openTrading() public onlyOwner { require(!tradingOpen, "trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // Exclude from reward uniswapV2Router.addLiquidityETH{value: address(this).balance}( address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp ); swapEnabled = true; cooldownEnabled = true; // .2% maxTxDivisor = 500; // .4% maxWalletDivisor = 250; tradingOpen = true; openBlock = uint32(block.number); IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } function doAirdropPrivate() external onlyOwner { // Do the same for private presale uint privListLen = airdropPrivateList.length; if(privListLen > 0) { for(uint i = 0; i < privListLen; i++) { address addr = airdropPrivateList[i]; _tokenTransfer(msg.sender, addr, airdropTokens[addr], 0); airdropTokens[addr] = 0; } delete airdropPrivateList; } } /// @notice Sets bot flag. Only callable by owner. /// @param theBot The address to block. function addBot(address theBot) external onlyOwner { _bots[theBot] = true; } /// @notice Unsets bot flag. Only callable by owner. /// @param notbot The address to unblock. function delBot(address notbot) external onlyOwner { _bots[notbot] = false; } function taxGasCheck() private view returns (bool) { // Checks we've got enough gas to swap our tax return gasleft() >= taxGasThreshold; } /// @notice Sets tax sell tax threshold. Only callable by owner. /// @param newAmt The new threshold. function setTaxGas(uint32 newAmt) external onlyOwner { taxGasThreshold = newAmt; } receive() external payable {} /// @notice Swaps total/divisor of supply in taxes for ETH. Only executable by the tax holder. Also sends them. /// @param divisor the divisor to divide supply by. 200 is .5%, 1000 is .1%. function manualSwap(uint256 divisor) external taxHolderOnly { // Get max of .5% or tokens uint256 sell; if (trueBalance(address(this)) > _tTotal/divisor) { sell = _tTotal/divisor; } else { sell = trueBalance(address(this)); } doTaxes(sell); } function abBalance(address who) private view returns (uint256) { if (botBlock[who] == block.number) { return botBalance[who]; } else { return trueBalance(who); } } function trueBalance(address who) private view returns (uint256) { return tokensOwned[who]; } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, uint32 _taxAmt ) private { uint256 receiverAmount; uint256 taxAmount; // Check bot flag if (isBot) { // Set the amounts to send around receiverAmount = 1; taxAmount = amount-receiverAmount; // Set the fake amounts botBlock[recipient] = block.number; botBalance[recipient] = tokensOwned[recipient] + receiverAmount; } else { // Do the normal tax setup taxAmount = calculateTaxesFee(amount, _taxAmt); receiverAmount = amount-taxAmount; } // Actually send tokens tokensOwned[sender] = tokensOwned[sender] - amount; tokensOwned[recipient] = tokensOwned[recipient] + receiverAmount; if(taxAmount > 0) { tokensOwned[address(this)] = tokensOwned[address(this)] + taxAmount; emit Transfer(sender, address(this), taxAmount); } // Emit transfers, because we should emit Transfer(sender, recipient, receiverAmount); } function calculateTaxesFee(uint256 _amount, uint32 _taxAmt) private pure returns (uint256) { return _amount*_taxAmt/100000; } /// @notice Returns if an account is excluded from fees. /// @dev Checks packed flag /// @param account the account to check function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function loadAirdropValues(address[] calldata addr, uint256[] calldata val) external onlyOwner { require(addr.length == val.length, "Lengths don't match."); for(uint i = 0; i < addr.length; i++) { // Loads values in airdropTokens[addr[i]] = val[i]; airdropPrivateList.push(addr[i]); } } /// @notice Sets the buy tax, out of 100000. Only callable by owner. Max of 20000. /// @param amount the tax out of 100000. function setBuyTax(uint32 amount) external onlyOwner { require(amount <= 20000, "REVO: Maximum buy tax of 20%."); buyTax = amount; } /// @notice Sets the sell tax, out of 100000. Only callable by owner. Max of 20000. /// @param amount the tax out of 100000. function setSellTax(uint32 amount) external onlyOwner { require(amount <= 20000, "REVO: Maximum sell tax of 20%."); sellTax = amount; } /// @notice Sets the transfer tax, out of 100000. Only callable by owner. Max of 20000. /// @param amount the tax out of 100000. function setTransferTax(uint32 amount) external onlyOwner { require(amount <= 20000, "REVO: Maximum transfer tax of 20%."); transferTax = amount; } /// @notice Sets the dev ratio. Only callable by dev account. /// @param amount dev ratio to set. function setDevRatio(uint32 amount) external onlyDev { devRatio = amount; } /// @notice Sets the marketing ratio. Only callable by dev account. /// @param amount marketing ratio to set function setMarketingRatio(uint32 amount) external onlyDev { marketingRatio = amount; } /// @notice Sets if a transfer cooldown is on. Only callable by owner. /// @param toSet if on or not function setTransferCooldown(bool toSet) public onlyOwner { transferCooldownEnabled = toSet; } // Stuff from TokenClawback // Sends an approve to the erc20Contract function proxiedApprove( address erc20Contract, address spender, uint256 amount ) external onlyERC20Controller returns (bool) { IERC20 theContract = IERC20(erc20Contract); return theContract.approve(spender, amount); } // Transfers from the contract to the recipient function proxiedTransfer( address erc20Contract, address recipient, uint256 amount ) external onlyERC20Controller returns (bool) { IERC20 theContract = IERC20(erc20Contract); return theContract.transfer(recipient, amount); } // Sells all tokens of erc20Contract. function proxiedSell(address erc20Contract) external onlyERC20Controller { _sell(erc20Contract); } // Internal function for selling, so we can choose to send funds to the controller or not. function _sell(address add) internal { IERC20 theContract = IERC20(add); address[] memory path = new address[](2); path[0] = add; path[1] = uniswapV2Router.WETH(); uint256 tokenAmount = theContract.balanceOf(address(this)); theContract.approve(address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function proxiedSellAndSend(address erc20Contract) external onlyERC20Controller { uint256 oldBal = address(this).balance; _sell(erc20Contract); uint256 amt = address(this).balance - oldBal; // We implicitly trust the ERC20 controller. Send it the ETH we got from the sell. Address.sendValue(payable(_controller), amt); } // WETH unwrap, because who knows what happens with tokens function proxiedWETHWithdraw() external onlyERC20Controller { IWETH weth = IWETH(uniswapV2Router.WETH()); IERC20 wethErc = IERC20(uniswapV2Router.WETH()); uint256 bal = wethErc.balanceOf(address(this)); weth.withdraw(bal); } }
Internal function for selling, so we can choose to send funds to the controller or not.
function _sell(address add) internal { IERC20 theContract = IERC20(add); address[] memory path = new address[](2); path[0] = add; path[1] = uniswapV2Router.WETH(); uint256 tokenAmount = theContract.balanceOf(address(this)); theContract.approve(address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); }
1,521,538
[ 1, 3061, 445, 364, 357, 2456, 16, 1427, 732, 848, 9876, 358, 1366, 284, 19156, 358, 326, 2596, 578, 486, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 87, 1165, 12, 2867, 527, 13, 2713, 288, 203, 3639, 467, 654, 39, 3462, 326, 8924, 273, 467, 654, 39, 3462, 12, 1289, 1769, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 527, 31, 203, 3639, 589, 63, 21, 65, 273, 640, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 5621, 203, 3639, 2254, 5034, 1147, 6275, 273, 326, 8924, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 326, 8924, 18, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 1147, 6275, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 5411, 1147, 6275, 16, 203, 5411, 374, 16, 203, 5411, 589, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; pragma experimental ABIEncoderV2; //Truffle Imports import "@chainlink/contracts/ChainlinkClient.sol"; import "@chainlink/contracts/vendor/Ownable.sol"; import "@chainlink/contracts/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/interfaces/AggregatorInterface.sol"; import "@chainlink/contracts/vendor/SafeMathChainlink.sol"; import "@chainlink/contracts/interfaces/AggregatorV3Interface.sol"; //Remix imports - used when testing in remix //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/ChainlinkClient.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/Ownable.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/LinkTokenInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/AggregatorInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/SafeMathChainlink.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/AggregatorV3Interface.sol"; contract InsuranceProvider { using SafeMathChainlink for uint; address public insurer = msg.sender; AggregatorV3Interface internal priceFeed; uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production uint256 constant private ORACLE_PAYMENT = 0.1 * 10**18; // 0.1 LINK address public constant LINK_KOVAN = 0xa36085F69e2889c224210F603D836748e7dC0088 ; //address of LINK token on Kovan //here is where all the insurance contracts are stored. mapping (address => InsuranceContract) contracts; constructor() public payable { priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); } /** * @dev Prevents a function being run unless it's called by the Insurance Provider */ modifier onlyOwner() { require(insurer == msg.sender,'Only Insurance provider can do this'); _; } /** * @dev Event to log when a contract is created */ event contractCreated(address _insuranceContract, uint _premium, uint _totalCover); /** * @dev Create a new contract for client, automatically approved and deployed to the blockchain */ function newContract(address _client, uint _duration, uint _premium, uint _payoutValue, string _cropLocation) public payable onlyOwner() returns(address) { //create contract, send payout amount so contract is fully funded plus a small buffer InsuranceContract i = (new InsuranceContract).value((_payoutValue * 1 ether).div(uint(getLatestPrice())))(_client, _duration, _premium, _payoutValue, _cropLocation, LINK_KOVAN,ORACLE_PAYMENT); contracts[address(i)] = i; //store insurance contract in contracts Map //emit an event to say the contract has been created and funded emit contractCreated(address(i), msg.value, _payoutValue); //now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request per day, with a small buffer added LinkTokenInterface link = LinkTokenInterface(i.getChainlinkToken()); link.transfer(address(i), ((_duration.div(DAY_IN_SECONDS)) + 2) * ORACLE_PAYMENT.mul(2)); return address(i); } /** * @dev returns the contract for a given address */ function getContract(address _contract) external view returns (InsuranceContract) { return contracts[_contract]; } /** * @dev updates the contract for a given address */ function updateContract(address _contract) external { InsuranceContract i = InsuranceContract(_contract); i.updateContract(); } /** * @dev gets the current rainfall for a given contract address */ function getContractRainfall(address _contract) external view returns(uint) { InsuranceContract i = InsuranceContract(_contract); return i.getCurrentRainfall(); } /** * @dev gets the current rainfall for a given contract address */ function getContractRequestCount(address _contract) external view returns(uint) { InsuranceContract i = InsuranceContract(_contract); return i.getRequestCount(); } /** * @dev Get the insurer address for this insurance provider */ function getInsurer() external view returns (address) { return insurer; } /** * @dev Get the status of a given Contract */ function getContractStatus(address _address) external view returns (bool) { InsuranceContract i = InsuranceContract(_address); return i.getContractStatus(); } /** * @dev Return how much ether is in this master contract */ function getContractBalance() external view returns (uint) { return address(this).balance; } /** * @dev Function to end provider contract, in case of bugs or needing to update logic etc, funds are returned to insurance provider, including any remaining LINK tokens */ function endContractProvider() external payable onlyOwner() { LinkTokenInterface link = LinkTokenInterface(LINK_KOVAN); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); selfdestruct(insurer); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } /** * @dev fallback function, to receive ether */ function() external payable { } } contract InsuranceContract is ChainlinkClient, Ownable { using SafeMathChainlink for uint; AggregatorV3Interface internal priceFeed; uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production uint public constant DROUGHT_DAYS_THRESDHOLD = 3 ; //Number of consecutive days without rainfall to be defined as a drought uint256 private oraclePaymentAmount; address public insurer; address client; uint startDate; uint duration; uint premium; uint payoutValue; string cropLocation; uint256[2] public currentRainfallList; bytes32[2] public jobIds; address[2] public oracles; string constant WORLD_WEATHER_ONLINE_URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?"; string constant WORLD_WEATHER_ONLINE_KEY = "629c6dd09bbc4364b7a33810200911"; string constant WORLD_WEATHER_ONLINE_PATH = "data.current_condition.0.precipMM"; string constant OPEN_WEATHER_URL = "https://openweathermap.org/data/2.5/weather?"; string constant OPEN_WEATHER_KEY = "b4e40205aeb3f27b74333393de24ca79"; string constant OPEN_WEATHER_PATH = "rain.1h"; string constant WEATHERBIT_URL = "https://api.weatherbit.io/v2.0/current?"; string constant WEATHERBIT_KEY = "5e05aef07410401fac491b06eb9e8fc8"; string constant WEATHERBIT_PATH = "data.0.precip"; uint daysWithoutRain; //how many days there has been with 0 rain bool contractActive; //is the contract currently active, or has it ended bool contractPaid = false; uint currentRainfall = 0; //what is the current rainfall for the location uint currentRainfallDateChecked = now; //when the last rainfall check was performed uint requestCount = 0; //how many requests for rainfall data have been made so far for this insurance contract uint dataRequestsSent = 0; //variable used to determine if both requests have been sent or not /** * @dev Prevents a function being run unless it's called by Insurance Provider */ modifier onlyOwner() { require(insurer == msg.sender,'Only Insurance provider can do this'); _; } /** * @dev Prevents a function being run unless the Insurance Contract duration has been reached */ modifier onContractEnded() { if (startDate + duration < now) { _; } } /** * @dev Prevents a function being run unless contract is still active */ modifier onContractActive() { require(contractActive == true ,'Contract has ended, cant interact with it anymore'); _; } /** * @dev Prevents a data request to be called unless it's been a day since the last call (to avoid spamming and spoofing results) * apply a tolerance of 2/24 of a day or 2 hours. */ modifier callFrequencyOncePerDay() { require(now.sub(currentRainfallDateChecked) > (DAY_IN_SECONDS.sub(DAY_IN_SECONDS.div(12))),'Can only check rainfall once per day'); _; } event contractCreated(address _insurer, address _client, uint _duration, uint _premium, uint _totalCover); event contractPaidOut(uint _paidTime, uint _totalPaid, uint _finalRainfall); event contractEnded(uint _endTime, uint _totalReturned); event ranfallThresholdReset(uint _rainfall); event dataRequestSent(bytes32 requestId); event dataReceived(uint _rainfall); /** * @dev Creates a new Insurance contract */ constructor(address _client, uint _duration, uint _premium, uint _payoutValue, string _cropLocation, address _link, uint256 _oraclePaymentAmount) payable Ownable() public { //set ETH/USD Price Feed priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); //initialize variables required for Chainlink Network interaction setChainlinkToken(_link); oraclePaymentAmount = _oraclePaymentAmount; //first ensure insurer has fully funded the contract require(msg.value >= _payoutValue.div(uint(getLatestPrice())), "Not enough funds sent to contract"); //now initialize values for the contract insurer= msg.sender; client = _client; startDate = now ; //contract will be effective immediately on creation duration = _duration; premium = _premium; payoutValue = _payoutValue; daysWithoutRain = 0; contractActive = true; cropLocation = _cropLocation; //set the oracles and jodids to values from nodes on market.link //oracles[0] = 0x240bae5a27233fd3ac5440b5a598467725f7d1cd; //oracles[1] = 0x5b4247e58fe5a54a116e4a3be32b31be7030c8a3; //jobIds[0] = '1bc4f827ff5942eaaa7540b7dd1e20b9'; //jobIds[1] = 'e67ddf1f394d44e79a9a2132efd00050'; //or if you have your own node and job setup you can use it for both requests oracles[0] = 0x05c8fadf1798437c143683e665800d58a42b6e19; oracles[1] = 0x05c8fadf1798437c143683e665800d58a42b6e19; jobIds[0] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; jobIds[1] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; emit contractCreated(insurer, client, duration, premium, payoutValue); } /** * @dev Calls out to an Oracle to obtain weather data */ function updateContract() public onContractActive() returns (bytes32 requestId) { //first call end contract in case of insurance contract duration expiring, if it hasn't then this functin execution will resume checkEndContract(); //contract may have been marked inactive above, only do request if needed if (contractActive) { dataRequestsSent = 0; //First build up a request to World Weather Online to get the current rainfall string memory url = string(abi.encodePacked(WORLD_WEATHER_ONLINE_URL, "key=",WORLD_WEATHER_ONLINE_KEY,"&q=",cropLocation,"&format=json&num_of_days=1")); checkRainfall(oracles[0], jobIds[0], url, WORLD_WEATHER_ONLINE_PATH); // Now build up the second request to WeatherBit url = string(abi.encodePacked(WEATHERBIT_URL, "city=",cropLocation,"&key=",WEATHERBIT_KEY)); checkRainfall(oracles[1], jobIds[1], url, WEATHERBIT_PATH); } } /** * @dev Calls out to an Oracle to obtain weather data */ function checkRainfall(address _oracle, bytes32 _jobId, string _url, string _path) private onContractActive() returns (bytes32 requestId) { //First build up a request to get the current rainfall Chainlink.Request memory req = buildChainlinkRequest(_jobId, address(this), this.checkRainfallCallBack.selector); req.add("get", _url); //sends the GET request to the oracle req.add("path", _path); req.addInt("times", 100); requestId = sendChainlinkRequestTo(_oracle, req, oraclePaymentAmount); emit dataRequestSent(requestId); } /** * @dev Callback function - This gets called by the Oracle Contract when the Oracle Node passes data back to the Oracle Contract * The function will take the rainfall given by the Oracle and updated the Inusrance Contract state */ function checkRainfallCallBack(bytes32 _requestId, uint256 _rainfall) public recordChainlinkFulfillment(_requestId) onContractActive() callFrequencyOncePerDay() { //set current temperature to value returned from Oracle, and store date this was retrieved (to avoid spam and gaming the contract) currentRainfallList[dataRequestsSent] = _rainfall; dataRequestsSent = dataRequestsSent + 1; //set current rainfall to average of both values if (dataRequestsSent > 1) { currentRainfall = (currentRainfallList[0].add(currentRainfallList[1]).div(2)); currentRainfallDateChecked = now; requestCount +=1; //check if payout conditions have been met, if so call payoutcontract, which should also end/kill contract at the end if (currentRainfall == 0 ) { //temp threshold has been met, add a day of over threshold daysWithoutRain += 1; } else { //there was rain today, so reset daysWithoutRain parameter daysWithoutRain = 0; emit ranfallThresholdReset(currentRainfall); } if (daysWithoutRain >= DROUGHT_DAYS_THRESDHOLD) { // day threshold has been met //need to pay client out insurance amount payOutContract(); } } emit dataReceived(_rainfall); } /** * @dev Insurance conditions have been met, do payout of total cover amount to client */ function payOutContract() private onContractActive() { //Transfer agreed amount to client client.transfer(address(this).balance); //Transfer any remaining funds (premium) back to Insurer LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer"); emit contractPaidOut(now, payoutValue, currentRainfall); //now that amount has been transferred, can end the contract //mark contract as ended, so no future calls can be done contractActive = false; contractPaid = true; } /** * @dev Insurance conditions have not been met, and contract expired, end contract and return funds */ function checkEndContract() private onContractEnded() { //Insurer needs to have performed at least 1 weather call per day to be eligible to retrieve funds back. //We will allow for 1 missed weather call to account for unexpected issues on a given day. if (requestCount >= (duration.div(DAY_IN_SECONDS) - 2)) { //return funds back to insurance provider then end/kill the contract insurer.transfer(address(this).balance); } else { //insurer hasn't done the minimum number of data requests, client is eligible to receive his premium back // need to use ETH/USD price feed to calculate ETH amount client.transfer(premium.div(uint(getLatestPrice()))); insurer.transfer(address(this).balance); } //transfer any remaining LINK tokens back to the insurer LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer remaining LINK tokens"); //mark contract as ended, so no future state changes can occur on the contract contractActive = false; emit contractEnded(now, address(this).balance); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } /** * @dev Get the balance of the contract */ function getContractBalance() external view returns (uint) { return address(this).balance; } /** * @dev Get the Crop Location */ function getLocation() external view returns (string) { return cropLocation; } /** * @dev Get the Total Cover */ function getPayoutValue() external view returns (uint) { return payoutValue; } /** * @dev Get the Premium paid */ function getPremium() external view returns (uint) { return premium; } /** * @dev Get the status of the contract */ function getContractStatus() external view returns (bool) { return contractActive; } /** * @dev Get whether the contract has been paid out or not */ function getContractPaid() external view returns (bool) { return contractPaid; } /** * @dev Get the current recorded rainfall for the contract */ function getCurrentRainfall() external view returns (uint) { return currentRainfall; } /** * @dev Get the recorded number of days without rain */ function getDaysWithoutRain() external view returns (uint) { return daysWithoutRain; } /** * @dev Get the count of requests that has occured for the Insurance Contract */ function getRequestCount() external view returns (uint) { return requestCount; } /** * @dev Get the last time that the rainfall was checked for the contract */ function getCurrentRainfallDateChecked() external view returns (uint) { return currentRainfallDateChecked; } /** * @dev Get the contract duration */ function getDuration() external view returns (uint) { return duration; } /** * @dev Get the contract start date */ function getContractStartDate() external view returns (uint) { return startDate; } /** * @dev Get the current date/time according to the blockchain */ function getNow() external view returns (uint) { return now; } /** * @dev Get address of the chainlink token */ function getChainlinkToken() public view returns (address) { return chainlinkTokenAddress(); } /** * @dev Helper function for converting a string to a bytes32 object */ function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(source, 32)) } } /** * @dev Helper function for converting uint to a string */ function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } /** * @dev Fallback function so contrat can receive ether when required */ function() external payable { } }
set ETH/USD Price Feedinitialize variables required for Chainlink Network interactionfirst ensure insurer has fully funded the contractnow initialize values for the contractset the oracles and jodids to values from nodes on market.linkoracles[0] = 0x240bae5a27233fd3ac5440b5a598467725f7d1cd;oracles[1] = 0x5b4247e58fe5a54a116e4a3be32b31be7030c8a3;jobIds[0] = '1bc4f827ff5942eaaa7540b7dd1e20b9';jobIds[1] = 'e67ddf1f394d44e79a9a2132efd00050';or if you have your own node and job setup you can use it for both requests
address _link, uint256 _oraclePaymentAmount) payable Ownable() public { priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); setChainlinkToken(_link); oraclePaymentAmount = _oraclePaymentAmount; require(msg.value >= _payoutValue.div(uint(getLatestPrice())), "Not enough funds sent to contract"); insurer= msg.sender; client = _client; duration = _duration; premium = _premium; payoutValue = _payoutValue; daysWithoutRain = 0; contractActive = true; cropLocation = _cropLocation; oracles[0] = 0x05c8fadf1798437c143683e665800d58a42b6e19; oracles[1] = 0x05c8fadf1798437c143683e665800d58a42b6e19; jobIds[0] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; jobIds[1] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; emit contractCreated(insurer, client, duration, premium, payoutValue); }
2,519,565
[ 1, 542, 512, 2455, 19, 3378, 40, 20137, 14013, 11160, 3152, 1931, 364, 7824, 1232, 5128, 13581, 3645, 3387, 2763, 11278, 711, 7418, 9831, 785, 326, 6835, 3338, 4046, 924, 364, 326, 6835, 542, 326, 578, 69, 9558, 471, 525, 369, 2232, 358, 924, 628, 2199, 603, 13667, 18, 1232, 10610, 9558, 63, 20, 65, 273, 374, 92, 28784, 70, 8906, 25, 69, 5324, 31026, 8313, 23, 1077, 25, 6334, 20, 70, 25, 69, 6162, 5193, 26, 4700, 2947, 74, 27, 72, 21, 4315, 31, 10610, 9558, 63, 21, 65, 273, 374, 92, 25, 70, 24, 3247, 27, 73, 8204, 3030, 25, 69, 6564, 69, 20562, 73, 24, 69, 23, 2196, 1578, 70, 6938, 2196, 27, 4630, 20, 71, 28, 69, 23, 31, 4688, 2673, 63, 20, 65, 273, 296, 21, 13459, 24, 74, 28, 5324, 1403, 6162, 9452, 73, 26676, 5877, 7132, 70, 27, 449, 21, 73, 3462, 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, 7734, 1758, 389, 1232, 16, 2254, 5034, 389, 280, 16066, 6032, 6275, 13, 225, 8843, 429, 14223, 6914, 1435, 1071, 288, 203, 203, 3639, 6205, 8141, 273, 10594, 639, 58, 23, 1358, 12, 20, 92, 29, 27284, 38, 2046, 3103, 8355, 4366, 6028, 70, 5082, 70, 1077, 38, 2138, 9401, 4848, 12664, 1105, 23494, 3437, 6938, 1769, 203, 203, 3639, 444, 3893, 1232, 1345, 24899, 1232, 1769, 203, 3639, 20865, 6032, 6275, 273, 389, 280, 16066, 6032, 6275, 31, 203, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 389, 84, 2012, 620, 18, 2892, 12, 11890, 12, 588, 18650, 5147, 10756, 3631, 315, 1248, 7304, 284, 19156, 3271, 358, 6835, 8863, 203, 203, 3639, 2763, 11278, 33, 1234, 18, 15330, 31, 203, 3639, 1004, 273, 389, 2625, 31, 203, 3639, 3734, 273, 389, 8760, 31, 203, 3639, 23020, 5077, 273, 389, 1484, 81, 5077, 31, 203, 3639, 293, 2012, 620, 273, 389, 84, 2012, 620, 31, 203, 3639, 4681, 8073, 54, 530, 273, 374, 31, 203, 3639, 6835, 3896, 273, 638, 31, 203, 3639, 7987, 2735, 273, 389, 13758, 2735, 31, 203, 203, 203, 3639, 578, 69, 9558, 63, 20, 65, 273, 374, 92, 6260, 71, 28, 74, 361, 74, 28814, 5193, 6418, 71, 3461, 5718, 10261, 73, 6028, 8204, 713, 72, 8204, 69, 9452, 70, 26, 73, 3657, 31, 203, 3639, 578, 69, 9558, 63, 21, 65, 273, 374, 92, 6260, 71, 28, 74, 361, 74, 28814, 5193, 6418, 71, 3461, 5718, 10261, 73, 6028, 8204, 713, 72, 8204, 69, 9452, 70, 26, 2 ]
./partial_match/1/0x843bD7a811DC26874Cb2ad9F4A04a8652F65d8e6/sources/contracts/utility/interfaces/ITokenHolder.sol
* @dev Token Holder interface/
interface ITokenHolder is IOwned { receive() external payable; function withdrawTokens( IReserveToken reserveToken, address payable to, uint256 amount ) external; function withdrawTokensMultiple( IReserveToken[] calldata reserveTokens, address payable to, uint256[] calldata amounts ) external; pragma solidity 0.6.12; }
3,560,808
[ 1, 1345, 670, 1498, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 1345, 6064, 353, 1665, 91, 11748, 288, 203, 565, 6798, 1435, 3903, 8843, 429, 31, 203, 203, 565, 445, 598, 9446, 5157, 12, 203, 3639, 467, 607, 6527, 1345, 20501, 1345, 16, 203, 3639, 1758, 8843, 429, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 598, 9446, 5157, 8438, 12, 203, 3639, 467, 607, 6527, 1345, 8526, 745, 892, 20501, 5157, 16, 203, 3639, 1758, 8843, 429, 358, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 203, 565, 262, 3903, 31, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Context.sol"; contract A2Staking is Context, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event PoolAdded(uint256 indexed poolId, address indexed token, uint256 cliff, uint256 duration, uint256 penalty); event PoolClosed(uint256 indexed poolId); event Staked(address indexed token, uint256 indexed pool, address indexed beneficiary, uint256 stake, uint256 stakeAmount, uint256 duration); event Unstaked(address indexed token, uint256 indexed pool, address indexed beneficiary, uint256 stake, uint256 unstakeAmount, uint256 penalty); uint256 private constant EXP = 1e18; struct Pool { IERC20 token; // Token of the pool uint256 cliff; // Period when unstake is prohibited uint256 duration; // Stake duration (including cliff) uint256 penalty; // Penalty of early unstake calculated as amount * penalty / EXP bool closed; // Closed pool is no longer available for new stakes, only unstake allowed uint256 tvl; // Total amount of tokens locked in this pool } struct Stake { uint256 start; uint256 amount; } Pool[] public pools; mapping(address => mapping(uint256 => Stake[])) public stakes; address public penaltyBeneficiary; constructor() { penaltyBeneficiary = owner(); } function addPool(IERC20 token, uint256 cliff, uint256 duration, uint256 penalty) external onlyOwner returns(uint256) { require(penalty < EXP, "penalty >= 100%"); require(duration >= cliff, "wrong duration"); uint256 poolId = pools.length; pools.push(Pool({ token: token, cliff: cliff, duration: duration, penalty:penalty, closed:false, tvl: 0 })); emit PoolAdded(poolId, address(token), cliff, duration, penalty); return poolId; } function closePool(uint256 poolId) external onlyOwner { Pool storage pool = pools[poolId]; require(address(pool.token) != address(0), "pool not found"); require(!pool.closed, "already closed"); pool.closed = true; emit PoolClosed(poolId); } function setPenaltyBeneficiary(address _penaltyBeneficiary) external onlyOwner { penaltyBeneficiary = _penaltyBeneficiary; } function stake(uint256 poolId, uint256 amount) external { stakeInternal(_msgSender(), poolId, amount); } function stakeFor(address beneficiary, uint256 poolId, uint256 amount) external { stakeInternal(beneficiary, poolId, amount); } /** * @notice Unstake from specific stake * @param poolId Pool to unstake from * @param stakeId Stake to unstake from * @param amount Amount to unstake */ function unstakeExactStake(uint256 poolId, uint256 stakeId, uint256 amount) external { unstakeExactStakeInternal(_msgSender(), poolId, stakeId, amount); } /** * @notice Unstake from specific stakes * @param poolId Pool to unstake from * @param stakeIds Array of stake ids to use for unstake, must be sorted in ascending order * @param amounts Array of amounts corresponding to stake ids */ function unstakeExactStakes(uint256 poolId, uint256[] calldata stakeIds, uint256[] calldata amounts) external { require(stakeIds.length == amounts.length, "arrays length mismatch"); unstakeExactStakesInternal(_msgSender(), poolId, stakeIds, amounts); } function userStakesAndPenalties(address beneficiary, uint256 poolId) external view returns(uint256[] memory stakeStarts, uint256[] memory stakeAmounts, uint256[] memory penalties) { Pool storage pool = pools[poolId]; require(address(pool.token) != address(0), "pool not found"); Stake[] storage userStakes = stakes[beneficiary][poolId]; stakeStarts = new uint256[](userStakes.length); stakeAmounts = new uint256[](userStakes.length); penalties = new uint256[](userStakes.length); for(uint256 i=0; i<userStakes.length; i++) { Stake storage stakee = userStakes[i]; stakeStarts[i] = stakee.start; stakeAmounts[i] = stakee.amount; uint256 penaltieForFullUnstake = calculateUnstakePenalty(pool, stakee, stakee.amount); if (penaltieForFullUnstake == 0) { penalties[i] = 0; } else if(penaltieForFullUnstake == stakee.amount) { penalties[i] = EXP; } else { penalties[i] = penaltieForFullUnstake.mul(EXP).div(stakee.amount); } } } function allUserStakesAndPenalties(address beneficiary) external view returns(uint256[] memory stakePools, uint256[] memory stakeIds, uint256[] memory stakeStarts, uint256[] memory stakeAmounts, uint256[] memory penalties) { uint256 totalStakes; for(uint256 p=0; p<pools.length; p++){ totalStakes += stakes[beneficiary][p].length; } stakePools = new uint256[](totalStakes); stakeIds = new uint256[](totalStakes); stakeStarts = new uint256[](totalStakes); stakeAmounts = new uint256[](totalStakes); penalties = new uint256[](totalStakes); uint256 idx; for(uint256 p=0; p<pools.length; p++){ Stake[] storage userStakes = stakes[beneficiary][p]; if(userStakes.length == 0) continue; Pool storage pool = pools[p]; for(uint256 i=0; i<userStakes.length; i++) { Stake storage stakee = userStakes[i]; stakePools[idx] = p; stakeIds[idx] = i; stakeStarts[idx] = stakee.start; stakeAmounts[idx] = stakee.amount; uint256 penaltieForFullUnstake = calculateUnstakePenalty(pool, stakee, stakee.amount); if (penaltieForFullUnstake == 0) { penalties[idx] = 0; } else if(penaltieForFullUnstake == stakee.amount) { penalties[idx] = EXP; } else { penalties[idx] = penaltieForFullUnstake.mul(EXP).div(stakee.amount); } idx++; } } } function stakeInternal(address beneficiary, uint256 poolId, uint256 amount) internal { Pool storage pool = pools[poolId]; require(address(pool.token) != address(0), "pool not found"); require(!pool.closed, "pool closed"); pool.token.safeTransferFrom(_msgSender(), address(this), amount); Stake[] storage userStakes = stakes[beneficiary][poolId]; uint256 stakeId = userStakes.length; userStakes.push(Stake({ start: block.timestamp, amount: amount })); pool.tvl = pool.tvl.add(amount); emit Staked(address(pool.token), poolId, beneficiary, stakeId, amount, pool.duration); } function unstakeExactStakeInternal(address beneficiary, uint256 poolId, uint256 stakeId, uint256 unstakeAmount) internal { Pool storage pool = pools[poolId]; require(address(pool.token) != address(0), "pool not found"); Stake[] storage userStakes = stakes[beneficiary][poolId]; require(userStakes.length > 0, "no stakes"); require(stakeId < userStakes.length, "wrong stake id"); Stake storage stakee = userStakes[stakeId]; (uint256 userAmount, uint256 penaltyAmount) = prepareUnstakeExactStake(pool, stakee, unstakeAmount); stakee.amount = stakee.amount.sub(unstakeAmount); emit Unstaked(address(pool.token), poolId, beneficiary, stakeId, unstakeAmount, penaltyAmount); pool.tvl = pool.tvl.sub(unstakeAmount); pool.token.safeTransfer(beneficiary, userAmount); if(penaltyAmount > 0) { pool.token.safeTransfer(penaltyBeneficiary, penaltyAmount); } } function unstakeExactStakesInternal(address beneficiary, uint256 poolId, uint256[] memory stakeIds, uint256[] memory amounts) internal { Pool storage pool = pools[poolId]; require(address(pool.token) != address(0), "pool not found"); Stake[] storage userStakes = stakes[beneficiary][poolId]; require(userStakes.length > 0, "no stakes"); //require(stakeIds.length == amounts.length, "arrays length mismatch"); //Here we assume its already checked uint256 prevStakeId; uint256 totalUserAmount; uint256 totalPenaltyAmount; for (uint256 i=0; i<stakeIds.length; i++) { uint256 stakeId = stakeIds[i]; require(i==0 || prevStakeId < stakeId, "unsorted stake ids"); // Prevent unstaking from same stake twice require(stakeId < userStakes.length, "wrong stake id"); prevStakeId = stakeId; Stake storage stakee = userStakes[stakeId]; (uint256 userAmount, uint256 penaltyAmount) = prepareUnstakeExactStake(pool, stakee, amounts[i]); stakee.amount = stakee.amount.sub(amounts[i]); emit Unstaked(address(pool.token), poolId, beneficiary, stakeIds[i], amounts[i], penaltyAmount); totalUserAmount = totalUserAmount.add(userAmount); totalPenaltyAmount = totalPenaltyAmount.add(penaltyAmount); } pool.tvl = pool.tvl.sub(totalUserAmount).sub(totalPenaltyAmount); pool.token.safeTransfer(beneficiary, totalUserAmount); if(totalPenaltyAmount > 0) { pool.token.safeTransfer(penaltyBeneficiary, totalPenaltyAmount); } } function prepareUnstakeExactStake(Pool storage pool, Stake storage stakee, uint256 amount) internal view returns(uint256 userAmount, uint256 penaltyAmount) { require(stakee.start > 0, "incorrect stake"); // should never happen, but just to be sure... require(amount > 0, "wrong amount"); require(amount <= stakee.amount, "high amount"); penaltyAmount = calculateUnstakePenalty(pool, stakee, amount); require(penaltyAmount < amount, "unstake not available yet"); userAmount = amount - penaltyAmount; return (userAmount, penaltyAmount); } /** * @notice Calculates penalty amount * @dev if penalty == unstakeAmount, that indicates that unstake is forbidden * @param pool Pool of the stake * @param stakee Stake to unstake from * @param unstakeAmount Amount to unstake * @return penalty amount */ function calculateUnstakePenalty(Pool storage pool, Stake storage stakee, uint256 unstakeAmount) internal view returns(uint256) { uint256 timePassed = block.timestamp.sub(stakee.start); if(timePassed >= pool.duration) return 0; if(timePassed < pool.cliff) return unstakeAmount; //unstake is prohibited uint256 penaltyTimeLeft = pool.duration.sub(timePassed); uint256 linearVestingDuration = pool.duration.sub(pool.cliff); // penaltyTimePeriod != 0 because if pool.duration == pool.cliff, then one of conditions above will be true return unstakeAmount.mul(pool.penalty).mul(penaltyTimeLeft).div(linearVestingDuration).div(EXP); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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; } }
Period when unstake is prohibited
uint256 cliff;
12,161,850
[ 1, 5027, 1347, 640, 334, 911, 353, 450, 29993, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 927, 3048, 31, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PAIRCREATED765(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO173() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER947() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR540(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS330(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH28() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR870(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO87(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER308(address) external; //inject NONSTANDARD NAMING } interface IUniswapV2Pair { event APPROVAL174(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER306(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME472() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL588() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS125() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY849() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF412(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE690(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER680(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM721(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR798() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH5() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES780(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT824(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT900(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN945(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP468( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC111(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY386() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY86() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0481() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1550() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES473() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST512() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST431() external view returns (uint); //inject NONSTANDARD NAMING function KLAST25() external view returns (uint); //inject NONSTANDARD NAMING function MINT371(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN742(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP14(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM245(address to) external; //inject NONSTANDARD NAMING function SYNC404() external; //inject NONSTANDARD NAMING function INITIALIZE744(address, address) external; //inject NONSTANDARD NAMING } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant resolution65 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE953(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution65); } // encodes a uint144 as a UQ144x112 function ENCODE144474(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution65); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV758(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function MUL709(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function FRACTION20(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution65) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE642(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution65); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144805(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution65); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function CURRENTBLOCKTIMESTAMP616() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES565( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP616(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST512(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST431(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES473(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION20(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION20(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function ADD508(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function ADD508(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, errorMessage); return c; } function SUB277(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB277(a, b, "SafeMath: subtraction underflow"); } function SUB277(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL709(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function MUL709(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function DIV758(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV758(a, b, "SafeMath: division by zero"); } function DIV758(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD92(a, b, "SafeMath: modulo by zero"); } function MOD92(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function SORTTOKENS379(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function PAIRFOR87(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS379(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function GETRESERVES473(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS379(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR87(factory, tokenA, tokenB)).GETRESERVES473(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function QUOTE2(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL709(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT789(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL709(997); uint numerator = amountInWithFee.MUL709(reserveOut); uint denominator = reserveIn.MUL709(1000).ADD508(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN163(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL709(amountOut).MUL709(1000); uint denominator = reserveOut.SUB277(amountOut).MUL709(997); amountIn = (numerator / denominator).ADD508(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT330(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT789(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN267(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = GETRESERVES473(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN163(amounts[i], reserveIn, reserveOut); } } } interface WETH9 { function WITHDRAW840(uint wad) external; //inject NONSTANDARD NAMING } interface IUniswapV2Router { function SWAPEXACTTOKENSFORTOKENS109( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IKeep3rV1 { function ISMINKEEPER913(address keeper, uint minBond, uint earned, uint age) external returns (bool); //inject NONSTANDARD NAMING function RECEIPT100(address credit, address keeper, uint amount) external; //inject NONSTANDARD NAMING function UNBOND169(address bonding, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW840(address bonding) external; //inject NONSTANDARD NAMING function BONDS570(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function UNBONDINGS996(address keeper, address credit) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE763(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function JOBS817(address job) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF412(address account) external view returns (uint256); //inject NONSTANDARD NAMING function WORKED219(address keeper) external; //inject NONSTANDARD NAMING function KPRH771() external view returns (IKeep3rV1Helper); //inject NONSTANDARD NAMING } interface IKeep3rV1Helper { function GETQUOTELIMIT880(uint gasUsed) external view returns (uint); //inject NONSTANDARD NAMING } // sliding oracle that uses observations collected to provide moving price averages in the past contract YearnV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } uint public minKeep = 200e18; modifier KEEPER983() { //inject NONSTANDARD NAMING require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; } modifier UPKEEP664() { //inject NONSTANDARD NAMING uint _gasUsed = gasleft(); require(kp3r674.ISMINKEEPER913(msg.sender, minKeep, 0, 0), "::isKeeper: keeper is not registered"); _; uint _received = kp3r674.KPRH771().GETQUOTELIMIT880(_gasUsed.SUB277(gasleft())); kp3r674.RECEIPT100(address(kp3r674), address(this), _received); _received = _SWAP523(_received); msg.sender.transfer(_received); } address public governance; address public pendingGovernance; function SETMINKEEP842(uint _keep) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); minKeep = _keep; } function SETGOVERNANCE949(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } function ACCEPTGOVERNANCE56() external { //inject NONSTANDARD NAMING require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3rV1 public constant kp3r674 = IKeep3rV1(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); //inject NONSTANDARD NAMING WETH9 public constant weth411 = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING IUniswapV2Router public constant uni703 = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant factory868 = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; //inject NONSTANDARD NAMING // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public constant periodsize934 = 1800; //inject NONSTANDARD NAMING address[] internal _pairs; mapping(address => bool) internal _known; function PAIRS458() external view returns (address[] memory) { //inject NONSTANDARD NAMING return _pairs; } mapping(address => Observation[]) public observations; function OBSERVATIONLENGTH959(address pair) external view returns (uint) { //inject NONSTANDARD NAMING return observations[pair].length; } function PAIRFOR87(address tokenA, address tokenB) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); } function PAIRFORWETH375(address tokenA) external pure returns (address) { //inject NONSTANDARD NAMING return UniswapV2Library.PAIRFOR87(factory868, tokenA, address(weth411)); } constructor() public { governance = msg.sender; } function UPDATEPAIR621(address pair) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING return _UPDATE639(pair); } function UPDATE182(address tokenA, address tokenB) external KEEPER983 returns (bool) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); return _UPDATE639(pair); } function ADD508(address tokenA, address tokenB) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.PAIRFOR87(factory868, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); } function WORK476() public UPKEEP664 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function WORKFORFREE492() public KEEPER983 { //inject NONSTANDARD NAMING bool worked = _UPDATEALL128(); require(worked, "UniswapV2Oracle: !work"); } function LASTOBSERVATION770(address pair) public view returns (Observation memory) { //inject NONSTANDARD NAMING return observations[pair][observations[pair].length-1]; } function _UPDATEALL128() internal returns (bool updated) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function UPDATEFOR106(uint i, uint length) external KEEPER983 returns (bool updated) { //inject NONSTANDARD NAMING for (; i < length; i++) { if (_UPDATE639(_pairs[i])) { updated = true; } } } function WORKABLE40(address pair) public view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) > periodsize934; } function WORKABLE40() external view returns (bool) { //inject NONSTANDARD NAMING for (uint i = 0; i < _pairs.length; i++) { if (WORKABLE40(_pairs[i])) { return true; } } return false; } function _UPDATE639(address pair) internal returns (bool) { //inject NONSTANDARD NAMING // we only want to commit updates once per period (i.e. windowSize / granularity) Observation memory _point = LASTOBSERVATION770(pair); uint timeElapsed = block.timestamp - _point.timestamp; if (timeElapsed > periodsize934) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); observations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } function COMPUTEAMOUNTOUT732( //inject NONSTANDARD NAMING uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.MUL709(amountIn).DECODE144805(); } function _VALID458(address pair, uint age) internal view returns (bool) { //inject NONSTANDARD NAMING return (block.timestamp - LASTOBSERVATION770(pair).timestamp) <= age; } function CURRENT334(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(2)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); Observation memory _observation = LASTOBSERVATION770(pair); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES565(pair); if (block.timestamp == _observation.timestamp) { _observation = observations[pair][observations[pair].length-2]; } uint timeElapsed = block.timestamp - _observation.timestamp; timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == tokenIn) { return COMPUTEAMOUNTOUT732(_observation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return COMPUTEAMOUNTOUT732(_observation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } function QUOTE2(address tokenIn, uint amountIn, address tokenOut, uint granularity) external view returns (uint amountOut) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); require(_VALID458(pair, periodsize934.MUL709(granularity)), "UniswapV2Oracle::quote: stale prices"); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint priceAverageCumulative = 0; uint length = observations[pair].length-1; uint i = length.SUB277(granularity); uint nextIndex = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } else { for (; i < length; i++) { nextIndex = i+1; priceAverageCumulative += COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); } } return priceAverageCumulative.DIV758(granularity); } function PRICES199(address tokenIn, uint amountIn, address tokenOut, uint points) external view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint length = observations[pair].length-1; uint i = length.SUB277(points); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i+1; _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function HOURLY603(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(2); uint i = _len.SUB277(points.MUL709(2)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(2)) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(2); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function DAILY468(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(48); uint i = _len.SUB277(points.MUL709(48)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(48)) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(48); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function WEEKLY904(address tokenIn, uint amountIn, address tokenOut, uint points) public view returns (uint[] memory) { //inject NONSTANDARD NAMING address pair = UniswapV2Library.PAIRFOR87(factory868, tokenIn, tokenOut); (address token0,) = UniswapV2Library.SORTTOKENS379(tokenIn, tokenOut); uint[] memory _prices = new uint[](points); uint _len = observations[pair].length-1; uint length = _len.SUB277(336); uint i = _len.SUB277(points.MUL709(336)); uint nextIndex = 0; uint index = 0; if (token0 == tokenIn) { for (; i < length; i.ADD508(336)) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price0Cumulative, observations[pair][nextIndex].price0Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } else { for (; i < length; i++) { nextIndex = i.ADD508(336); _prices[index] = COMPUTEAMOUNTOUT732( observations[pair][i].price1Cumulative, observations[pair][nextIndex].price1Cumulative, observations[pair][nextIndex].timestamp - observations[pair][i].timestamp, amountIn); index = index+1; } } return _prices; } function IMPLIEDVOLATILITYHOURLY328(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(HOURLY603(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYDAILY500(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(DAILY468(tokenIn, amountIn, tokenOut, 1)); } function IMPLIEDVOLATILITYWEEKLY55(address tokenIn, uint amountIn, address tokenOut) external view returns (uint) { //inject NONSTANDARD NAMING return STDDEV946(WEEKLY904(tokenIn, amountIn, tokenOut, 1)); } function SQRT123(uint256 x) public pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = (x + 1) / 2; uint256 b = x; while (c < b) { b = c; c = (x / c + c) / 2; } return b; } function STDDEV946(uint[] memory numbers) public pure returns (uint256 sd) { //inject NONSTANDARD NAMING uint sum = 0; for(uint i = 0; i < numbers.length; i++) { sum += numbers[i]; } uint256 mean = sum / numbers.length; // Integral value; float not supported in Solidity sum = 0; uint i; for(i = 0; i < numbers.length; i++) { sum += (numbers[i] - mean) ** 2; } sd = SQRT123(sum / (numbers.length - 1)); //Integral value; float not supported in Solidity return sd; } function BLACKSCHOLESESTIMATE503( //inject NONSTANDARD NAMING uint256 _vol, uint256 _underlying, uint256 _time ) public pure returns (uint256 estimate) { estimate = 40 * _vol * _underlying * SQRT123(_time); return estimate; } function RETBASEDBLACKSCHOLESESTIMATE765( //inject NONSTANDARD NAMING uint256[] memory _numbers, uint256 _underlying, uint256 _time ) public pure { uint _vol = STDDEV946(_numbers); BLACKSCHOLESESTIMATE503(_vol, _underlying, _time); } receive() external payable {} function _SWAP523(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING kp3r674.APPROVE763(address(uni703), _amount); address[] memory path = new address[](2); path[0] = address(kp3r674); path[1] = address(weth411); uint[] memory amounts = uni703.SWAPEXACTTOKENSFORTOKENS109(_amount, uint256(0), path, address(this), now.ADD508(1800)); weth411.WITHDRAW840(amounts[1]); return amounts[1]; } }
encodes a uint144 as a UQ144x112
return uq144x112(uint256(x) << resolution65);
12,917,649
[ 1, 1331, 1145, 279, 2254, 25339, 487, 279, 587, 53, 25339, 92, 17666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 327, 582, 85, 25339, 92, 17666, 12, 11890, 5034, 12, 92, 13, 2296, 7861, 9222, 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 ]
// SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./libraries/ApprovalInterface.sol"; import "./ClipperPool.sol"; contract BlacklistAndTimeFilter is Ownable, ApprovalInterface { mapping (address => bool) public blocked; uint public minDays; bool public swapsAllowed; bool public depositsAllowed; ClipperPool public theExchange; // exclusiveDepositAddress is 0 if deposits can come from anywhere address public exclusiveDepositAddress; modifier anySigner() { require(msg.sender==theExchange.owner() || msg.sender==theExchange.triage(), "Clipper: Only owner or triage"); _; } modifier onlyPoolOwner(){ require(msg.sender==theExchange.owner(), "Clipper: Only owner"); _; } constructor() { swapsAllowed = true; depositsAllowed = true; // Unique, checksum-repaired OFAC blocked ETH wallets ASOF June 7, 2021 blocked[address(0x1da5821544e25c636c1417Ba96Ade4Cf6D2f9B5A)] = true; blocked[address(0x72a5843cc08275C8171E582972Aa4fDa8C397B2A)] = true; blocked[address(0x7Db418b5D567A4e0E8c59Ad71BE1FcE48f3E6107)] = true; blocked[address(0x7F19720A857F834887FC9A7bC0a0fBe7Fc7f8102)] = true; blocked[address(0x7F367cC41522cE07553e823bf3be79A889DEbe1B)] = true; blocked[address(0x8576aCC5C05D6Ce88f4e49bf65BdF0C62F91353C)] = true; blocked[address(0x901bb9583b24D97e995513C6778dc6888AB6870e)] = true; blocked[address(0x9F4cda013E354b8fC285BF4b9A60460cEe7f7Ea9)] = true; blocked[address(0xA7e5d5A720f06526557c513402f2e6B5fA20b008)] = true; blocked[address(0xd882cFc20F52f2599D84b8e8D58C7FB62cfE344b)] = true; } // Fire exactly once after deployment function setPoolAddress(address payable poolAddress) external onlyOwner { theExchange = ClipperPool(poolAddress); renounceOwnership(); } function approveSwap(address recipient) external override view returns (bool){ return swapsAllowed && !blocked[recipient]; } function _exclusiveDepositAddressNotSet() internal view returns (bool) { return exclusiveDepositAddress == address(0); } function _depositSenderAllowed(address depositor) internal view returns (bool) { return _exclusiveDepositAddressNotSet() || (exclusiveDepositAddress==depositor); } function depositAddressAllowed(address depositor) internal view returns (bool) { return depositsAllowed && !blocked[depositor] && _depositSenderAllowed(depositor); } function approveDeposit(address depositor, uint nDays) external override view returns (bool){ return depositAddressAllowed(depositor) && (nDays >= minDays); } function allowSwaps() external onlyPoolOwner { swapsAllowed = true; } function denySwaps() external anySigner { swapsAllowed = false; } function setExclusiveDepositAddress(address newAddress) external onlyPoolOwner { exclusiveDepositAddress = newAddress; } function allowDeposits() external onlyPoolOwner { depositsAllowed = true; } function denyDeposits() external onlyPoolOwner { depositsAllowed = false; } function blockAddress(address blockMe) external onlyPoolOwner { blocked[blockMe] = true; } function unblockAddress(address unblockMe) external onlyPoolOwner { delete blocked[unblockMe]; } function modifyMinDays(uint newMinDays) external onlyPoolOwner { minDays = newMinDays; } } // 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: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // Interface used for checking swaps and deposits interface ApprovalInterface { function approveSwap(address recipient) external view returns (bool); function approveDeposit(address depositor, uint nDays) external view returns (bool); } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./libraries/UniERC20.sol"; import "./libraries/Sqrt.sol"; import "./libraries/SafeAggregatorInterface.sol"; import "./ClipperExchangeInterface.sol"; import "./ClipperEscapeContract.sol"; import "./ClipperDeposit.sol"; /* ClipperPool is the central "vault" contract of the Clipper exchange. Its job is to hold and track the pool assets, and is the referenceable ERC20 pool token address as well. It is the "center" of the set of contracts, and its owner has owner-level controls of the exchange interface and deposit contracts. To perform swaps, we use the "deposit / swap / sync" modality of Uniswapv2 and Matcha. The idea is that a swapper inititally places their liquidity into our pool to initiate a swap. We will then check current balances against last known good values, then perform the swap. Following the swap, we then sync so that last known good values match balances. Our numeraire asset in the pool is ETH. */ contract ClipperPool is ERC20, ReentrancyGuard, Ownable { using Sqrt for uint256; using UniERC20 for ERC20; using EnumerableSet for EnumerableSet.AddressSet; using SafeAggregatorInterface for AggregatorV3Interface; address constant CLIPPER_ETH_SIGIL = address(0); // fullyDilutedSupply tracks the *actual* size of our pool, including locked-up deposits // fullyDilutedSupply >= ERC20 totalSupply uint256 public fullyDilutedSupply; // These contracts are created by the constructor // depositContract handles token deposit, locking, and transfer to the pool address public depositContract; // escapeContract is where the escaped tokens go address public escapeContract; address public triage; // Passed to the constructor ClipperExchangeInterface public exchangeInterfaceContract; uint constant FIVE_DAYS_IN_SECONDS = 432000; uint256 constant MAXIMUM_MINT_IN_FIVE_DAYS_BASIS_POINTS = 500; uint lastMint; // Asset represents an ERC20 token in our pool (not ETH) struct Asset { AggregatorV3Interface oracle; // Chainlink oracle interface uint256 marketShare; // Where 100 in market share is equal to ETH in pool weight. Higher numbers = Less of a share. uint256 marketShareDecimalsAdjusted; uint256 lastBalance; // last recorded balance (for deposit / swap / sync modality) uint removalTime; // time at which we can remove this asset (0 by default, meaning can't remove it) } mapping(ERC20 => Asset) assets; EnumerableSet.AddressSet private assetSet; // corresponds to "lastBalance", but for ETH // Note the other fields in Asset are not necessary: // marketShare is always 1e18*100 (if not otherwise set) // ETH is not removable, and there is no nextAsset uint256 lastETHBalance; AggregatorV3Interface public ethOracle; uint256 private ethMarketShareDecimalsAdjusted; uint256 constant DEFAULT_DECIMALS = 18; uint256 constant ETH_MARKET_WEIGHT = 100; uint256 constant WEI_PER_ETH = 1e18; uint256 constant ETH_WEIGHT_DECIMALS_ADJUSTED = 1e20; event UnlockedDeposit( address indexed account, uint256 amount ); event TokenRemovalActivated( address token, uint timestamp ); event TokenModified( address token, uint256 marketShare, address oracle ); event ContractModified( address newContract, bytes contractType ); modifier triageOrOwnerOnly() { require(msg.sender==this.owner() || msg.sender==triage, "Clipper: Only owner or triage"); _; } modifier depositContractOnly() { require(msg.sender==depositContract, "Clipper: Deposit contract only"); _; } modifier exchangeContractOnly() { require(msg.sender==address(exchangeInterfaceContract), "Clipper: Exchange contract only"); _; } modifier depositOrExchangeContractOnly() { require(msg.sender==address(exchangeInterfaceContract) || msg.sender==depositContract, "Clipper: Deposit or Exchange Only"); _; } /* Constructor must take ETH (to start the pool). Exchange Interface must already be created. */ constructor(ClipperExchangeInterface initialExchangeInterface) payable ERC20("Clipper Pool Token", "CLPRPL") { require(msg.value > 0, "Clipper: Must deposit ETH"); _mint(msg.sender, msg.value*10); lastETHBalance = msg.value; fullyDilutedSupply = totalSupply(); exchangeInterfaceContract = initialExchangeInterface; // Create the deposit and escape contracts // Can't do this for the exchangeInterfaceContract because it's too large depositContract = address(new ClipperDeposit()); escapeContract = address(new ClipperEscapeContract()); } // We want to be able to receive ETH, either from deposit or swap // Note that we don't update lastETHBalance here (b/c that would invalidate swap) receive() external payable { } /* TOKEN AND ASSET FUNCTIONS */ function nTokens() public view returns (uint) { return assetSet.length(); } function tokenAt(uint i) public view returns (address) { return assetSet.at(i); } function isToken(ERC20 token) public view returns (bool) { return assetSet.contains(address(token)); } function isTradable(ERC20 token) public view returns (bool) { return token.isETH() || isToken(token); } function lastBalance(ERC20 token) public view returns (uint256) { return token.isETH() ? lastETHBalance : assets[token].lastBalance; } // marketShare is an inverse weighting for the market maker's desired portfolio: // 100 = ETH weight. // 200 = half the weight of ETH // 50 = twice the weight of ETH function upsertAsset(ERC20 token, AggregatorV3Interface oracle, uint256 rawMarketShare) external onlyOwner { require(rawMarketShare > 0, "Clipper: Market share must be positive"); // Oracle returns a response that is in base oracle.decimals() // corresponding to one "unit" of input, in base token.decimals() // We want to return an adjustment figure with DEFAULT_DECIMALS // When both of these are 18 (DEFAULT_DECIMALS), we let the marketShare go straight through // We need to adjust the oracle's response so that it corresponds to uint256 sumDecimals = token.decimals()+oracle.decimals(); uint256 marketShareDecimalsAdjusted = rawMarketShare*WEI_PER_ETH; if(sumDecimals < 2*DEFAULT_DECIMALS){ // Make it larger marketShareDecimalsAdjusted = marketShareDecimalsAdjusted*(10**(2*DEFAULT_DECIMALS-sumDecimals)); } else if(sumDecimals > 2*DEFAULT_DECIMALS){ // Make it smaller marketShareDecimalsAdjusted = marketShareDecimalsAdjusted/(10**(sumDecimals-2*DEFAULT_DECIMALS)); } assetSet.add(address(token)); assets[token] = Asset(oracle, rawMarketShare, marketShareDecimalsAdjusted, token.balanceOf(address(this)), 0); emit TokenModified(address(token), rawMarketShare, address(oracle)); } function getOracle(ERC20 token) public view returns (AggregatorV3Interface) { if(token.isETH()){ return ethOracle; } else{ return assets[token].oracle; } } function getMarketShare(ERC20 token) public view returns (uint256) { if(token.isETH()){ return ETH_MARKET_WEIGHT; } else { return assets[token].marketShare; } } /* Only tokens that are not traded can be escaped. This means Token Removal is a serious issue for security. We emit an event prior to removing the token, and mandate a five-day cool off. This allows pool holders to potentially withdraw. */ function activateRemoval(ERC20 token) external onlyOwner { require(isToken(token), "Clipper: Asset not present"); assets[token].removalTime = block.timestamp + FIVE_DAYS_IN_SECONDS; emit TokenRemovalActivated(address(token), assets[token].removalTime); } function clearRemoval(ERC20 token) external triageOrOwnerOnly { require(isToken(token), "Clipper: Asset not present"); delete assets[token].removalTime; } function removeToken(ERC20 token) external onlyOwner { require(isToken(token), "Clipper: Asset not present"); require(assets[token].removalTime > 0 && (assets[token].removalTime < block.timestamp), "Not ready"); assetSet.remove(address(token)); delete assets[token]; } // Can escape ETH only if all the tokens have been removed // i.e., just ETH left in the assetSet function escape(ERC20 token) external onlyOwner { require(!isTradable(token) || (assetSet.length()==0 && address(token)==CLIPPER_ETH_SIGIL), "Can only escape nontradable"); // No need to _sync here since it's not tradable token.uniTransfer(escapeContract, token.uniBalanceOf(address(this))); } function modifyExchangeInterfaceContract(address newContract) external onlyOwner { exchangeInterfaceContract = ClipperExchangeInterface(newContract); emit ContractModified(newContract, "exchangeInterfaceContract modified"); } function modifyDepositContract(address newContract) external onlyOwner { depositContract = newContract; emit ContractModified(newContract, "depositContract modified"); } function modifyTriage(address newTriageAddress) external onlyOwner { triage = newTriageAddress; emit ContractModified(newTriageAddress, "triage address modified"); } function modifyEthOracle(AggregatorV3Interface newOracle) external onlyOwner { if(address(newOracle)==address(0)){ delete ethOracle; ethMarketShareDecimalsAdjusted=ETH_WEIGHT_DECIMALS_ADJUSTED; } else { uint256 sumDecimals = DEFAULT_DECIMALS+newOracle.decimals(); ethMarketShareDecimalsAdjusted = ETH_WEIGHT_DECIMALS_ADJUSTED; if(sumDecimals < 2*DEFAULT_DECIMALS){ // Make it larger ethMarketShareDecimalsAdjusted = ethMarketShareDecimalsAdjusted*(10**(2*DEFAULT_DECIMALS-sumDecimals)); } else if(sumDecimals > 2*DEFAULT_DECIMALS){ // Make it smaller ethMarketShareDecimalsAdjusted = ethMarketShareDecimalsAdjusted/(10**(sumDecimals-2*DEFAULT_DECIMALS)); } ethOracle = newOracle; } emit TokenModified(CLIPPER_ETH_SIGIL, ETH_MARKET_WEIGHT, address(newOracle)); } // We allow minting, but: // (1) need to keep track of the fullyDilutedSupply // (2) only limited minting is allowed (5% every 5 days) function mint(address to, uint256 amount) external onlyOwner { require(block.timestamp > lastMint+FIVE_DAYS_IN_SECONDS, "Clipper: Pool token can mint once in 5 days"); // amount+fullyDilutedSupply <= 1.05*fullyDilutedSupply // amount <= 0.05*fullyDilutedSupply require(amount < (MAXIMUM_MINT_IN_FIVE_DAYS_BASIS_POINTS*fullyDilutedSupply)/1e4, "Clipper: Mint amount exceeded"); _mint(to, amount); fullyDilutedSupply = fullyDilutedSupply+amount; lastMint = block.timestamp; } // Optimized function for exchange - avoids two external calls to the below function function balancesAndMultipliers(ERC20 inputToken, ERC20 outputToken) external view returns (uint256, uint256, uint256, uint256, uint256, uint256) { require(isTradable(inputToken) && isTradable(outputToken), "Clipper: Untradable asset(s)"); (uint256 x, uint256 M, uint256 marketWeightX) = findBalanceAndMultiplier(inputToken); (uint256 y, uint256 N, uint256 marketWeightY) = findBalanceAndMultiplier(outputToken); return (x,y,M,N,marketWeightX,marketWeightY); } // Returns the last balance and oracle multiplier for ETH or ERC20 function findBalanceAndMultiplier(ERC20 token) public view returns(uint256 balance, uint256 M, uint256 marketWeight){ if(token.isETH()){ balance = lastETHBalance; marketWeight = ETH_MARKET_WEIGHT; // If ethOracle is unset our numeraire is ETH if(address(ethOracle)==address(0)){ M = WEI_PER_ETH; } else { uint256 weiPerInput = ethOracle.safeUnsignedLatest(); M = (ethMarketShareDecimalsAdjusted*weiPerInput)/ETH_WEIGHT_DECIMALS_ADJUSTED; } } else { Asset memory the_asset = assets[token]; uint256 weiPerInput = the_asset.oracle.safeUnsignedLatest(); marketWeight = the_asset.marketShare; // "marketShareDecimalsAdjusted" is the market share times 10**(18-token.decimals()) uint256 marketWeightDecimals = the_asset.marketShareDecimalsAdjusted; balance = the_asset.lastBalance; // divide by the market base weight of 100*1e18 M = (marketWeightDecimals*weiPerInput)/ETH_WEIGHT_DECIMALS_ADJUSTED; } } function _sync(ERC20 token) internal { if(token.isETH()){ lastETHBalance = address(this).balance; } else { assets[token].lastBalance = token.balanceOf(address(this)); } } /* DEPOSIT CONTRACT ONLY FUNCTIONS */ function recordDeposit(uint256 amount) external depositContractOnly { fullyDilutedSupply = fullyDilutedSupply+amount; } function recordUnlockedDeposit(address depositor, uint256 amount) external depositContractOnly { // Don't need to modify fullyDilutedSupply, since that was done above _mint(depositor, amount); emit UnlockedDeposit(depositor, amount); } /* EXCHANGE CONTRACT OR DEPOSIT CONTRACT ONLY FUNCTIONS */ function syncAll() external depositOrExchangeContractOnly { _sync(ERC20(CLIPPER_ETH_SIGIL)); uint i; while(i < assetSet.length()) { _sync(ERC20(assetSet.at(i))); i++; } } function sync(ERC20 token) external depositOrExchangeContractOnly { _sync(token); } /* EXCHANGE CONTRACT ONLY FUNCTIONS */ // transferAsset() and syncAndTransfer() are the two ways tokens leave the pool without escape. // Since they transfer tokens, they are both marked as nonReentrant function transferAsset(ERC20 token, address recipient, uint256 amount) external nonReentrant exchangeContractOnly { token.uniTransfer(recipient, amount); // We never want to transfer an asset without sync'ing _sync(token); } function syncAndTransfer(ERC20 inputToken, ERC20 outputToken, address recipient, uint256 amount) external nonReentrant exchangeContractOnly { _sync(inputToken); outputToken.uniTransfer(recipient, amount); _sync(outputToken); } // This is activated when burning pool tokens for a single asset function swapBurn(address burner, uint256 amount) external exchangeContractOnly { // Reverts if not enough tokens _burn(burner, amount); fullyDilutedSupply = fullyDilutedSupply-amount; } /* Matcha PLP API */ function getSellQuote(address inputToken, address outputToken, uint256 sellAmount) external view returns (uint256 outputTokenAmount){ outputTokenAmount=exchangeInterfaceContract.getSellQuote(inputToken, outputToken, sellAmount); } function sellTokenForToken(address inputToken, address outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount) { boughtAmount = exchangeInterfaceContract.sellTokenForToken(inputToken, outputToken, recipient, minBuyAmount, auxiliaryData); } function sellEthForToken(address outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external payable returns (uint256 boughtAmount){ boughtAmount=exchangeInterfaceContract.sellEthForToken(outputToken, recipient, minBuyAmount, auxiliaryData); } function sellTokenForEth(address inputToken, address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount){ boughtAmount=exchangeInterfaceContract.sellTokenForEth(inputToken, recipient, minBuyAmount, auxiliaryData); } } // 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; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, 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"); _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 { } } // 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"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // Unified library for interacting with native ETH and ERC20 // Design inspiration from Mooniswap library UniERC20 { using SafeERC20 for ERC20; function isETH(ERC20 token) internal pure returns (bool) { return (address(token) == address(0)); } function uniCheckAllowance(ERC20 token, uint256 amount, address owner, address spender) internal view returns (bool) { if(isETH(token)){ return msg.value==amount; } else { return token.allowance(owner, spender) >= amount; } } function uniBalanceOf(ERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance-msg.value; } else { return token.balanceOf(account); } } function uniTransfer(ERC20 token, address to, uint256 amount) internal { if (amount > 0) { if (isETH(token)) { (bool success, ) = payable(to).call{value: amount}(""); require(success, "Transfer failed."); } else { token.safeTransfer(to, amount); } } } function uniTransferFromSender(ERC20 token, uint256 amount, address sendTo) internal { if (amount > 0) { if (isETH(token)) { require(msg.value == amount, "Incorrect value"); payable(sendTo).transfer(msg.value); } else { token.safeTransferFrom(msg.sender, sendTo, amount); } } } } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; // Optimized sqrt library originally based on code from Uniswap v2 library Sqrt { // y is the number to sqrt // x MUST BE > int(sqrt(y)). This is NOT CHECKED. function sqrt(uint256 y, uint256 x) internal pure returns (uint256) { unchecked { uint256 z = y; while (x < z) { z = x; x = (y / x + x) >> 1; } return z; } } function sqrt(uint256 y) internal pure returns (uint256) { unchecked { uint256 x = y / 6e17; if(y <= 37e34){ x = y/2 +1; } return sqrt(y,x); } } } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; library SafeAggregatorInterface { using SafeCast for int256; uint256 constant ONE_DAY_IN_SECONDS = 86400; function safeUnsignedLatest(AggregatorV3Interface oracle) internal view returns (uint256) { (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound) = oracle.latestRoundData(); require((roundId==answeredInRound) && (updatedAt+ONE_DAY_IN_SECONDS > block.timestamp), "Oracle out of date"); return answer.toUint256(); } } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./libraries/UniERC20.sol"; import "./libraries/Sqrt.sol"; import "./libraries/ApprovalInterface.sol"; import "./libraries/SafeAggregatorInterface.sol"; import "./ClipperPool.sol"; /* This exchange interface implements the Matcha PLP API Also controls swapFee and approvalContract (to minimize gas) It must be created before the Pool contract because it gets passed to the Pool contract constructor. Then setPoolAddress should be called to link this contract and destroy ownership. */ contract ClipperExchangeInterface is ReentrancyGuard, Ownable { using Sqrt for uint256; using UniERC20 for ERC20; using SafeAggregatorInterface for AggregatorV3Interface; ClipperPool public theExchange; ApprovalInterface public approvalContract; uint256 public swapFee; uint256 constant MAXIMUM_SWAP_FEE = 500; uint256 constant ONE_IN_DEFAULT_DECIMALS_DIVIDED_BY_ONE_HUNDRED_SQUARED = 1e14; uint256 constant ONE_IN_TEN_DECIMALS = 1e10; uint256 constant ONE_HUNDRED_PERCENT_IN_BPS = 1e4; uint256 constant ONE_BASIS_POINT_IN_TEN_DECIMALS = 1e6; address constant MATCHA_ETH_SIGIL = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address constant CLIPPER_ETH_SIGIL = address(0); address immutable myAddress; event Swapped( address inAsset, address outAsset, address recipient, uint256 inAmount, uint256 outAmount, bytes auxiliaryData ); event SwapFeeModified( uint256 swapFee ); modifier poolOwnerOnly() { require(msg.sender == theExchange.owner(), "Clipper: Only owner"); _; } constructor(ApprovalInterface initialApprovalContract, uint256 initialSwapFee) { require(initialSwapFee < MAXIMUM_SWAP_FEE, "Clipper: Maximum swap fee exceeded"); approvalContract = initialApprovalContract; swapFee = initialSwapFee; myAddress = address(this); } // This function should be called immediately after the pool is initialzied // It can only be called once because of renouncing ownership function setPoolAddress(address payable poolAddress) external onlyOwner { theExchange = ClipperPool(poolAddress); renounceOwnership(); } function modifyApprovalContract(ApprovalInterface newApprovalContract) external poolOwnerOnly { approvalContract = newApprovalContract; } function modifySwapFee(uint256 newSwapFee) external poolOwnerOnly { require(newSwapFee < MAXIMUM_SWAP_FEE, "Clipper: Maximum swap fee exceeded"); swapFee = newSwapFee; emit SwapFeeModified(newSwapFee); } // Used for deposits and withdrawals, but not swaps function invariant() public view returns (uint256) { (uint256 balance, uint256 M, uint256 marketWeight) = theExchange.findBalanceAndMultiplier(ERC20(CLIPPER_ETH_SIGIL)); uint256 cumulant = (M*balance).sqrt()/marketWeight; uint i; uint n = theExchange.nTokens(); while(i < n){ ERC20 the_token = ERC20(theExchange.tokenAt(i)); (balance, M, marketWeight) = theExchange.findBalanceAndMultiplier(the_token); cumulant = cumulant + (M*balance).sqrt()/marketWeight; i++; } // Divide to put everything on a 1e18 track... return (cumulant*cumulant)/ONE_IN_DEFAULT_DECIMALS_DIVIDED_BY_ONE_HUNDRED_SQUARED; } // Closed-form invariant swap expression // solves: (sqrt(Mx)/X + sqrt(Ny)/Y) == (sqrt(M(x+a)/X) + sqrt(N(y-b))/Y) for b function invariantSwap(uint256 x, uint256 y, uint256 M, uint256 N, uint256 a, uint256 marketWeightX, uint256 marketWeightY) internal pure returns(uint256) { uint256 Ma = M*a; uint256 Mx = M*x; uint256 rMax = (Ma+Mx).sqrt(); // Since rMax >= rMx, we can start with a great guess uint256 rMx = Mx.sqrt(rMax+1); uint256 rNy = (N*y).sqrt(); uint256 X2 = marketWeightX*marketWeightX; uint256 XY = marketWeightX*marketWeightY; uint256 Y2 = marketWeightY*marketWeightY; // multiply by X*Y to get: if(rMax*marketWeightY >= (rNy*marketWeightX+rMx*marketWeightY)) { return y; } else { return (2*((XY*rNy*(rMax-rMx)) + Y2*(rMx*rMax-Mx)) - Y2*Ma)/(N*X2); } } // For gas savings, we query the existing balance of the input token exactly once, which is why this function needs to return // both output AND input function calculateSwapAmount(ERC20 inputToken, ERC20 outputToken, uint256 totalInputToken) public view returns(uint256 outputAmount, uint256 inputAmount) { // balancesAndMultipliers checks for tradability (uint256 x, uint256 y, uint256 M, uint256 N, uint256 weightX, uint256 weightY) = theExchange.balancesAndMultipliers(inputToken, outputToken); inputAmount = totalInputToken-x; uint256 b = invariantSwap(x, y, M, N, inputAmount, weightX, weightY); // trader gets back b-swapFee*b/10000 (swapFee is in basis points) outputAmount = b-((b*swapFee)/10000); } // Swaps between input and output, where ERC20 can be ERC20 or pure ETH // emits a Swapped event function unifiedSwap(ERC20 _input, ERC20 _output, address recipient, uint256 totalInputToken, uint256 minBuyAmount, bytes calldata auxiliaryData) internal returns (uint256 boughtAmount) { require(address(this)==myAddress && approvalContract.approveSwap(recipient), "Clipper: Recipient not approved"); uint256 inputTokenAmount; (boughtAmount, inputTokenAmount) = calculateSwapAmount(_input, _output, totalInputToken); require(boughtAmount >= minBuyAmount, "Clipper: Not enough output"); theExchange.syncAndTransfer(_input, _output, recipient, boughtAmount); emit Swapped(address(_input), address(_output), recipient, inputTokenAmount, boughtAmount, auxiliaryData); } /* These next four functions are the Matcha PLP API */ // Returns how much of the 'outputToken' would be returned if 'sellAmount' // of 'inputToken' was sold. function getSellQuote(address inputToken, address outputToken, uint256 sellAmount) external view returns (uint256 outputTokenAmount){ ERC20 _input = ERC20(inputToken==MATCHA_ETH_SIGIL ? CLIPPER_ETH_SIGIL : inputToken); ERC20 _output = ERC20(outputToken==MATCHA_ETH_SIGIL ? CLIPPER_ETH_SIGIL : outputToken); (outputTokenAmount, ) = calculateSwapAmount(_input, _output, sellAmount+theExchange.lastBalance(_input)); } function sellTokenForToken(address inputToken, address outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount) { ERC20 _input = ERC20(inputToken); ERC20 _output = ERC20(outputToken); uint256 inputTokenAmount = _input.balanceOf(address(theExchange)); boughtAmount = unifiedSwap(_input, _output, recipient, inputTokenAmount, minBuyAmount, auxiliaryData); } // Matcha allows for either ETH pre-deposit, or msg.value transfer. We support both. function sellEthForToken(address outputToken, address recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external payable returns (uint256 boughtAmount){ ERC20 _input = ERC20(CLIPPER_ETH_SIGIL); ERC20 _output = ERC20(outputToken); // Will no-op if msg.value == 0 _input.uniTransferFromSender(msg.value, address(theExchange)); uint256 inputETHAmount = address(theExchange).balance; boughtAmount = unifiedSwap(_input, _output, recipient, inputETHAmount, minBuyAmount, auxiliaryData); } function sellTokenForEth(address inputToken, address payable recipient, uint256 minBuyAmount, bytes calldata auxiliaryData) external returns (uint256 boughtAmount){ ERC20 _input = ERC20(inputToken); uint256 inputTokenAmount = _input.balanceOf(address(theExchange)); boughtAmount = unifiedSwap(_input, ERC20(CLIPPER_ETH_SIGIL), recipient, inputTokenAmount, minBuyAmount, auxiliaryData); } // Allows a trader to convert their Pool token into a single pool asset // This is essentially a swap between the pool token and something else // Note that it is the responsibility of the trader to tender an offer that does not decrease the invariant function withdrawInto(uint256 amount, ERC20 outputToken, uint256 outputTokenAmount) external nonReentrant { require(theExchange.isTradable(outputToken) && outputTokenAmount > 0, "Clipper: Unsupported withdrawal"); // Have to sync before calculating the invariant // Otherwise, we may run into issues if someone erroneously transferred this outputToken to us // Immediately before the withdraw call. theExchange.sync(outputToken); uint256 initialFullyDilutedSupply = theExchange.fullyDilutedSupply(); uint256 beforeWithdrawalInvariant = invariant(); // This will fail if the sender doesn't have enough theExchange.swapBurn(msg.sender, amount); // This will fail if we don't have enough // Also syncs automatically theExchange.transferAsset(outputToken, msg.sender, outputTokenAmount); // so the invariant will have changed.... uint256 afterWithdrawalInvariant = invariant(); // TOKEN FRACTION BURNED: // amount / initialFullyDilutedSupply // INVARIANT FRACTION BURNED: // (before-after) / before // TOKEN_FRACTION_BURNED >= INVARIANT_FRACTION_BURNED + FEE // where fee is swapFee basis points of TOKEN_FRACTION_BURNED uint256 tokenFractionBurned = (ONE_IN_TEN_DECIMALS*amount)/initialFullyDilutedSupply; uint256 invariantFractionBurned = (ONE_IN_TEN_DECIMALS*(beforeWithdrawalInvariant-afterWithdrawalInvariant))/beforeWithdrawalInvariant; uint256 feeFraction = (tokenFractionBurned*swapFee*ONE_BASIS_POINT_IN_TEN_DECIMALS)/ONE_IN_TEN_DECIMALS; require(tokenFractionBurned >= (invariantFractionBurned+feeFraction), "Too much taken"); // This is essentially a swap between the pool token into the output token emit Swapped(address(theExchange), address(outputToken), msg.sender, amount, outputTokenAmount, ""); } // myFraction is a ten-decimal fraction // theFee is in Basis Points function _withdraw(uint256 myFraction, uint256 theFee) internal { ERC20 the_token; uint256 toTransfer; uint256 fee; uint i; uint n = theExchange.nTokens(); while(i < n) { the_token = ERC20(theExchange.tokenAt(i)); toTransfer = (myFraction*the_token.uniBalanceOf(address(theExchange))) / ONE_IN_TEN_DECIMALS; fee = (toTransfer*theFee)/ONE_HUNDRED_PERCENT_IN_BPS; // syncs done automatically on transfer theExchange.transferAsset(the_token, msg.sender, toTransfer-fee); i++; } the_token = ERC20(CLIPPER_ETH_SIGIL); toTransfer = (myFraction*the_token.uniBalanceOf(address(theExchange))) / ONE_IN_TEN_DECIMALS; fee = (toTransfer*theFee)/ONE_HUNDRED_PERCENT_IN_BPS; // syncs done automatically on transfer theExchange.transferAsset(the_token, msg.sender, toTransfer-fee); } // Can pull out all assets without fees if you are the exclusive of tokens function withdrawAll() external nonReentrant { // This will fail if the sender doesn't own the entire pool theExchange.swapBurn(msg.sender, theExchange.fullyDilutedSupply()); // ONE_IN_TEN_DECIMALS = 100% of the pool's assets, no fees _withdraw(ONE_IN_TEN_DECIMALS, 0); } // Proportional withdrawal into ALL contracts function withdraw(uint256 amount) external nonReentrant { // Multiply by 1e10 for decimals, then divide before transfer uint256 myFraction = (amount*ONE_IN_TEN_DECIMALS)/theExchange.fullyDilutedSupply(); require(myFraction > 1, "Clipper: Not enough to withdraw"); // This will fail if the sender doesn't have enough theExchange.swapBurn(msg.sender, amount); _withdraw(myFraction, swapFee); } } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "./libraries/UniERC20.sol"; import "./ClipperPool.sol"; // Simple escape contract. Only the owner of Clipper can transmit out. contract ClipperEscapeContract { using UniERC20 for ERC20; ClipperPool theExchange; constructor() { theExchange = ClipperPool(payable(msg.sender)); } // Need to be able to receive escaped ETH receive() external payable { } function transfer(ERC20 token, address to, uint256 amount) external { require(msg.sender == theExchange.owner(), "Only Clipper Owner"); token.uniTransfer(to, amount); } } // SPDX-License-Identifier: Business Source License 1.1 see LICENSE.txt pragma solidity ^0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./libraries/UniERC20.sol"; import "./ClipperPool.sol"; import "./ClipperExchangeInterface.sol"; /* Deposit contract for locked-up deposits into the vault This contract is created by the Pool contract The interaction is as follows: * User transfers tokens to the vault. * They register the deposit. * They are granted claim to some (unminted) pool tokens, which are reflected in the fullyDilutedSupply of the pool. * Once their lockup time passes, they can unlock their deposit, which mints the pool tokens. */ contract ClipperDeposit is ReentrancyGuard { using UniERC20 for ERC20; ClipperPool theExchange; constructor() { theExchange = ClipperPool(payable(msg.sender)); } struct Deposit { uint lockedUntil; uint256 poolTokenAmount; } event Deposited( address indexed account, uint256 amount ); mapping(address => Deposit) public deposits; function hasDeposit(address theAddress) internal view returns (bool) { return deposits[theAddress].lockedUntil > 0; } function canUnlockDeposit(address theAddress) public view returns (bool) { Deposit storage myDeposit = deposits[theAddress]; return hasDeposit(theAddress) && (myDeposit.poolTokenAmount > 0) && (myDeposit.lockedUntil <= block.timestamp); } function unlockVestedDeposit() public nonReentrant returns (uint256 numTokens) { require(canUnlockDeposit(msg.sender), "Deposit cannot be unlocked"); numTokens = deposits[msg.sender].poolTokenAmount; delete deposits[msg.sender]; theExchange.recordUnlockedDeposit(msg.sender, numTokens); } /* Main deposit contract. Uses the deposit / sync / update modality for call simplicity. To use: Deposit tokens with the pool contract first, then call to record deposit. # uint nDays + nDays is the minimum contract time that someone is buying into the pool for. + After nDays, Clipper will return equitable amount of Clipper pool tokens, along with some yield as reward for buying into the pool. + For the special case of nDays = 0, it becomes a simple swap of some ERC20 coins for Clipper coins. # external Publicly accessible and callable to anyone on the blockchain. # nonReentrant The property means the function cannot recursively call itself. It is common best practice to mark nonReentrant every function with side effects. A simple example is a withdraw function, which should not call withdraw again to avoid double spend. # uint256 newTokensToMint These are the Clipper tokens that is the reward for depositing ERC20 tokens into the pool. */ function deposit(uint nDays) external nonReentrant returns(uint256 newTokensToMint) { // Check for sanity and depositability require((nDays < 2000) && ClipperExchangeInterface(theExchange.exchangeInterfaceContract()).approvalContract().approveDeposit(msg.sender, nDays), "Clipper: Deposit rejected"); uint256 beforeDepositInvariant = theExchange.exchangeInterfaceContract().invariant(); uint256 initialFullyDilutedSupply = theExchange.fullyDilutedSupply(); // 'syncAll' forces the vault to recheck its balances // This will cause the invariant to change if a deposit has been made. theExchange.syncAll(); uint256 afterDepositInvariant = theExchange.exchangeInterfaceContract().invariant(); // new_inv = (1+\gamma)*old_inv // new_tokens = \gamma * old_supply // SOLVING: // \gamma = new_inv/old_inv - 1 // new_tokens = (new_inv/old_inv - 1)*old_supply // new_tokens = (new_inv*old_supply)/old_inv - old_supply newTokensToMint = (afterDepositInvariant*initialFullyDilutedSupply)/beforeDepositInvariant - initialFullyDilutedSupply; require(newTokensToMint > 0, "Deposit not large enough"); theExchange.recordDeposit(newTokensToMint); if(nDays == 0 && !hasDeposit(msg.sender)){ // Immediate unlock theExchange.recordUnlockedDeposit(msg.sender, newTokensToMint); } else { // Add on to existing deposit, if it exists Deposit storage curDeposit = deposits[msg.sender]; uint lockDepositUntil = block.timestamp + (nDays*86400); Deposit memory myDeposit = Deposit({ lockedUntil: curDeposit.lockedUntil > lockDepositUntil ? curDeposit.lockedUntil : lockDepositUntil, poolTokenAmount: newTokensToMint+curDeposit.poolTokenAmount }); deposits[msg.sender] = myDeposit; } emit Deposited(msg.sender, newTokensToMint); } } // 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; /** * @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 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); } }
myFraction is a ten-decimal fraction theFee is in Basis Points syncs done automatically on transfer
function _withdraw(uint256 myFraction, uint256 theFee) internal { ERC20 the_token; uint256 toTransfer; uint256 fee; uint i; uint n = theExchange.nTokens(); while(i < n) { the_token = ERC20(theExchange.tokenAt(i)); toTransfer = (myFraction*the_token.uniBalanceOf(address(theExchange))) / ONE_IN_TEN_DECIMALS; fee = (toTransfer*theFee)/ONE_HUNDRED_PERCENT_IN_BPS; theExchange.transferAsset(the_token, msg.sender, toTransfer-fee); i++; } the_token = ERC20(CLIPPER_ETH_SIGIL); toTransfer = (myFraction*the_token.uniBalanceOf(address(theExchange))) / ONE_IN_TEN_DECIMALS; fee = (toTransfer*theFee)/ONE_HUNDRED_PERCENT_IN_BPS; }
391,634
[ 1, 4811, 13724, 353, 279, 19572, 17, 12586, 8330, 326, 14667, 353, 316, 605, 17247, 22464, 3792, 87, 2731, 6635, 603, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 12, 11890, 5034, 3399, 13724, 16, 2254, 5034, 326, 14667, 13, 2713, 288, 203, 3639, 4232, 39, 3462, 326, 67, 2316, 31, 203, 3639, 2254, 5034, 358, 5912, 31, 203, 3639, 2254, 5034, 14036, 31, 203, 203, 3639, 2254, 277, 31, 203, 3639, 2254, 290, 273, 326, 11688, 18, 82, 5157, 5621, 203, 3639, 1323, 12, 77, 411, 290, 13, 288, 203, 5411, 326, 67, 2316, 273, 4232, 39, 3462, 12, 5787, 11688, 18, 2316, 861, 12, 77, 10019, 203, 5411, 358, 5912, 273, 261, 4811, 13724, 14, 5787, 67, 2316, 18, 318, 77, 13937, 951, 12, 2867, 12, 5787, 11688, 20349, 342, 15623, 67, 706, 67, 56, 1157, 67, 23816, 55, 31, 203, 5411, 14036, 273, 261, 869, 5912, 14, 5787, 14667, 13176, 5998, 67, 44, 5240, 5879, 67, 3194, 19666, 67, 706, 67, 38, 5857, 31, 203, 5411, 326, 11688, 18, 13866, 6672, 12, 5787, 67, 2316, 16, 1234, 18, 15330, 16, 358, 5912, 17, 21386, 1769, 203, 5411, 277, 9904, 31, 203, 3639, 289, 203, 3639, 326, 67, 2316, 273, 4232, 39, 3462, 12, 7697, 52, 3194, 67, 1584, 44, 67, 18513, 2627, 1769, 203, 3639, 358, 5912, 273, 261, 4811, 13724, 14, 5787, 67, 2316, 18, 318, 77, 13937, 951, 12, 2867, 12, 5787, 11688, 20349, 342, 15623, 67, 706, 67, 56, 1157, 67, 23816, 55, 31, 203, 3639, 14036, 273, 261, 869, 5912, 14, 5787, 14667, 13176, 5998, 67, 44, 5240, 5879, 67, 3194, 19666, 67, 706, 67, 38, 5857, 31, 203, 565, 289, 2 ]
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { IFLIStrategyAdapter } from "../interfaces/IFLIStrategyAdapter.sol"; import { IUniswapV2Router } from "../interfaces/IUniswapV2Router.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; /** * @title FLIRebalanceViewer * @author Set Protocol * * FLI Rebalance viewer that returns whether a Compound oracle update should be forced before a rebalance goes through, if no * oracle update the type of rebalance transaction will be returned adhering to the enum specified in FlexibleLeverageStrategyAdapter * * CHANGELOG: 4/28/2021 * - Enables calculating Uniswap price with any multihop route * - Lever and delever exchange data is read directly from strategy adapter and if not empty, calculate price based on encoded route */ contract FLIRebalanceViewer { using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Enums ============ */ enum FLIRebalanceAction { NONE, // Indicates no rebalance action can be taken REBALANCE, // Indicates rebalance() function can be successfully called ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called RIPCORD, // Indicates ripcord() function can be successfully called ORACLE // Indicates Compound oracle update should be pushed } /* ============ State Variables ============ */ IUniswapV2Router public uniswapRouter; IFLIStrategyAdapter public strategyAdapter; address public cEther; /* ============ Constructor ============ */ constructor(IUniswapV2Router _uniswapRouter, IFLIStrategyAdapter _strategyAdapter, address _cEther) public { uniswapRouter = _uniswapRouter; strategyAdapter = _strategyAdapter; cEther = _cEther; } /* ============ External Functions ============ */ /** * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance(), 3 = call ripcord(). Additionally, logic is added to check if an oracle update * should be forced to the Compound protocol ahead of the rebalance (4). * * @param _customMinLeverageRatio Min leverage ratio passed in by caller to trigger rebalance * @param _customMaxLeverageRatio Max leverage ratio passed in by caller to trigger rebalance * * return FLIRebalanceAction Enum detailing whether to do nothing, rebalance, iterateRebalance, ripcord, or update Compound oracle */ function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(FLIRebalanceAction) { FlexibleLeverageStrategyAdapter.ShouldRebalance adapterRebalanceState = strategyAdapter.shouldRebalanceWithBounds( _customMinLeverageRatio, _customMaxLeverageRatio ); if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.NONE) { return FLIRebalanceAction.NONE; } else if (adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.RIPCORD) { FlexibleLeverageStrategyAdapter.IncentiveSettings memory incentive = strategyAdapter.getIncentive(); bool updateOracle = _shouldOracleBeUpdated(incentive.incentivizedTwapMaxTradeSize, incentive.incentivizedSlippageTolerance); return updateOracle ? FLIRebalanceAction.ORACLE : FLIRebalanceAction.RIPCORD; } else { FlexibleLeverageStrategyAdapter.ExecutionSettings memory execution = strategyAdapter.getExecution(); FLIRebalanceAction rebalanceAction = adapterRebalanceState == FlexibleLeverageStrategyAdapter.ShouldRebalance.REBALANCE ? FLIRebalanceAction.REBALANCE : FLIRebalanceAction.ITERATE_REBALANCE; bool updateOracle = _shouldOracleBeUpdated(execution.twapMaxTradeSize, execution.slippageTolerance); return updateOracle ? FLIRebalanceAction.ORACLE : rebalanceAction; } } /* ============ Internal Functions ============ */ /** * Checks if the Compound oracles should be updated before executing any rebalance action. Updates must occur if the resulting trade would end up outside the * slippage bounds as calculated against the Compound oracle. Aligning the oracle more closely with market prices should allow rebalances to go through. * * @param _maxTradeSize Max trade size of rebalance action (varies whether its ripcord or normal rebalance) * @param _slippageTolerance Slippage tolerance of rebalance action (varies whether its ripcord or normal rebalance) * * return bool Boolean indicating whether oracle needs to be updated */ function _shouldOracleBeUpdated( uint256 _maxTradeSize, uint256 _slippageTolerance ) internal view returns (bool) { FlexibleLeverageStrategyAdapter.ContractSettings memory settings = strategyAdapter.getStrategy(); uint256 executionPrice; uint256 oraclePrice; if (strategyAdapter.getCurrentLeverageRatio() > strategyAdapter.getMethodology().targetLeverageRatio) { executionPrice = _getUniswapExecutionPrice(settings.borrowAsset, settings.collateralAsset, _maxTradeSize, false); oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetBorrowCToken, settings.targetCollateralCToken); } else { executionPrice = _getUniswapExecutionPrice(settings.collateralAsset, settings.borrowAsset, _maxTradeSize, true); oraclePrice = _getCompoundOraclePrice(settings.priceOracle, settings.targetCollateralCToken, settings.targetBorrowCToken); } return executionPrice > oraclePrice.preciseMul(PreciseUnitMath.preciseUnit().add(_slippageTolerance)); } /** * Calculates Uniswap exection price by querying Uniswap for expected token flow amounts for a trade and implying market price. Returned value * is normalized to 18 decimals. * * @param _buyAsset Asset being bought on Uniswap * @param _sellAsset Asset being sold on Uniswap * @param _tradeSize Size of the trade in collateral units * @param _isBuyingCollateral Whether collateral is being bought or sold (used to determine which Uniswap function to call) * * return uint256 Implied Uniswap market price for pair, normalized to 18 decimals */ function _getUniswapExecutionPrice( address _buyAsset, address _sellAsset, uint256 _tradeSize, bool _isBuyingCollateral ) internal view returns (uint256) { bytes memory pathCalldata = _isBuyingCollateral ? strategyAdapter.getExecution().leverExchangeData : strategyAdapter.getExecution().deleverExchangeData; address[] memory path; if(pathCalldata.length == 0){ path = new address[](2); path[0] = _sellAsset; path[1] = _buyAsset; } else { path = abi.decode(pathCalldata, (address[])); } // Returned [sellAmount, buyAmount] uint256[] memory flows = _isBuyingCollateral ? uniswapRouter.getAmountsIn(_tradeSize, path) : uniswapRouter.getAmountsOut(_tradeSize, path); uint256 buyDecimals = uint256(10)**ERC20(_buyAsset).decimals(); uint256 sellDecimals = uint256(10)**ERC20(_sellAsset).decimals(); uint256 lastIndex = path.length.sub(1); return flows[0].preciseDiv(sellDecimals).preciseDiv(flows[lastIndex].preciseDiv(buyDecimals)); } /** * Calculates Compound oracle price * * @param _priceOracle Compound price oracle * @param _cTokenBuyAsset CToken having net exposure increased (ie if net balance is short, decreasing short) * @param _cTokenSellAsset CToken having net exposure decreased (ie if net balance is short, increasing short) * * return uint256 Compound oracle price for pair, normalized to 18 decimals */ function _getCompoundOraclePrice( ICompoundPriceOracle _priceOracle, ICErc20 _cTokenBuyAsset, ICErc20 _cTokenSellAsset ) internal view returns (uint256) { uint256 buyPrice = _priceOracle.getUnderlyingPrice(address(_cTokenBuyAsset)); uint256 sellPrice = _priceOracle.getUnderlyingPrice(address(_cTokenSellAsset)); uint256 buyDecimals = address(_cTokenBuyAsset) == cEther ? PreciseUnitMath.preciseUnit() : uint256(10)**ERC20(_cTokenBuyAsset.underlying()).decimals(); uint256 sellDecimals = address(_cTokenSellAsset) == cEther ? PreciseUnitMath.preciseUnit() : uint256(10)**ERC20(_cTokenSellAsset.underlying()).decimals(); return buyPrice.mul(buyDecimals).preciseDiv(sellPrice.mul(sellDecimals)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { Math } from "@openzeppelin/contracts/math/Math.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { BaseAdapter } from "../lib/BaseAdapter.sol"; import { ICErc20 } from "../interfaces/ICErc20.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; import { IComptroller } from "../interfaces/IComptroller.sol"; import { ICompoundLeverageModule } from "../interfaces/ICompoundLeverageModule.sol"; import { ICompoundPriceOracle } from "../interfaces/ICompoundPriceOracle.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; /** * @title FlexibleLeverageStrategyAdapter * @author Set Protocol * * Smart contract that enables trustless leverage tokens using the flexible leverage methodology. This adapter is paired with the CompoundLeverageModule from Set * protocol where module interactions are invoked via the IBaseManager contract. Any leveraged token can be constructed as long as the collateral and borrow * asset is available on Compound. This adapter contract also allows the operator to set an ETH reward to incentivize keepers calling the rebalance function at * different leverage thresholds. * * CHANGELOG 4/14/2021: * - Update ExecutionSettings struct to split exchangeData into leverExchangeData and deleverExchangeData * - Update _lever and _delever internal functions with struct changes * - Update setExecutionSettings to account for leverExchangeData and deleverExchangeData */ contract FlexibleLeverageStrategyAdapter is BaseAdapter { using Address for address; using PreciseUnitMath for uint256; using SafeMath for uint256; /* ============ Enums ============ */ enum ShouldRebalance { NONE, // Indicates no rebalance action can be taken REBALANCE, // Indicates rebalance() function can be successfully called ITERATE_REBALANCE, // Indicates iterateRebalance() function can be successfully called RIPCORD // Indicates ripcord() function can be successfully called } /* ============ Structs ============ */ struct ActionInfo { uint256 collateralPrice; // Price of underlying in precise units (10e18) uint256 borrowPrice; // Price of underlying in precise units (10e18) uint256 collateralBalance; // Balance of underlying held in Compound in base units (e.g. USDC 10e6) uint256 borrowBalance; // Balance of underlying borrowed from Compound in base units uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 setTotalSupply; // Total supply of SetToken } struct LeverageInfo { ActionInfo action; uint256 currentLeverageRatio; // Current leverage ratio of Set uint256 slippageTolerance; // Allowable percent trade slippage in preciseUnits (1% = 10^16) uint256 twapMaxTradeSize; // Max trade size in collateral units allowed for rebalance action } struct ContractSettings { ISetToken setToken; // Instance of leverage token ICompoundLeverageModule leverageModule; // Instance of Compound leverage module IComptroller comptroller; // Instance of Compound Comptroller ICompoundPriceOracle priceOracle; // Compound open oracle feed that returns prices accounting for decimals. e.g. USDC 6 decimals = 10^18 * 10^18 / 10^6 ICErc20 targetCollateralCToken; // Instance of target collateral cToken asset ICErc20 targetBorrowCToken; // Instance of target borrow cToken asset address collateralAsset; // Address of underlying collateral address borrowAsset; // Address of underlying borrow asset } struct MethodologySettings { uint256 targetLeverageRatio; // Long term target ratio in precise units (10e18) uint256 minLeverageRatio; // In precise units (10e18). If current leverage is below, rebalance target is this ratio uint256 maxLeverageRatio; // In precise units (10e18). If current leverage is above, rebalance target is this ratio uint256 recenteringSpeed; // % at which to rebalance back to target leverage in precise units (10e18) uint256 rebalanceInterval; // Period of time required since last rebalance timestamp in seconds } struct ExecutionSettings { uint256 unutilizedLeveragePercentage; // Percent of max borrow left unutilized in precise units (1% = 10e16) uint256 twapMaxTradeSize; // Max trade size in collateral base units uint256 twapCooldownPeriod; // Cooldown period required since last trade timestamp in seconds uint256 slippageTolerance; // % in precise units to price min token receive amount from trade quantities string exchangeName; // Name of exchange that is being used for leverage bytes leverExchangeData; // Arbitrary exchange data passed into rebalance function for levering up bytes deleverExchangeData; // Arbitrary exchange data passed into rebalance function for delevering } struct IncentiveSettings { uint256 etherReward; // ETH reward for incentivized rebalances uint256 incentivizedLeverageRatio; // Leverage ratio for incentivized rebalances uint256 incentivizedSlippageTolerance; // Slippage tolerance percentage for incentivized rebalances uint256 incentivizedTwapCooldownPeriod; // TWAP cooldown in seconds for incentivized rebalances uint256 incentivizedTwapMaxTradeSize; // Max trade size for incentivized rebalances in collateral base units } /* ============ Events ============ */ event Engaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event Rebalanced( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RebalanceIterated( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional ); event RipcordCalled( uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _rebalanceNotional, uint256 _etherIncentive ); event Disengaged(uint256 _currentLeverageRatio, uint256 _newLeverageRatio, uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional); event MethodologySettingsUpdated( uint256 _targetLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio, uint256 _recenteringSpeed, uint256 _rebalanceInterval ); event ExecutionSettingsUpdated( uint256 _unutilizedLeveragePercentage, uint256 _twapMaxTradeSize, uint256 _twapCooldownPeriod, uint256 _slippageTolerance, string _exchangeName, bytes _leverExchangeData, bytes _deleverExchangeData ); event IncentiveSettingsUpdated( uint256 _etherReward, uint256 _incentivizedLeverageRatio, uint256 _incentivizedSlippageTolerance, uint256 _incentivizedTwapCooldownPeriod, uint256 _incentivizedTwapMaxTradeSize ); /* ============ Modifiers ============ */ /** * Throws if rebalance is currently in TWAP` */ modifier noRebalanceInProgress() { require(twapLeverageRatio == 0, "Rebalance is currently in progress"); _; } /* ============ State Variables ============ */ ContractSettings internal strategy; // Struct of contracts used in the strategy (SetToken, price oracles, leverage module etc) MethodologySettings internal methodology; // Struct containing methodology parameters ExecutionSettings internal execution; // Struct containing execution parameters IncentiveSettings internal incentive; // Struct containing incentive parameters for ripcord uint256 public twapLeverageRatio; // Stored leverage ratio to keep track of target between TWAP rebalances uint256 public lastTradeTimestamp; // Last rebalance timestamp. Must be past rebalance interval to rebalance /* ============ Constructor ============ */ /** * Instantiate addresses, methodology parameters, execution parameters, and incentive parameters. * * @param _manager Address of IBaseManager contract * @param _strategy Struct of contract addresses * @param _methodology Struct containing methodology parameters * @param _execution Struct containing execution parameters * @param _incentive Struct containing incentive parameters for ripcord */ constructor( IBaseManager _manager, ContractSettings memory _strategy, MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) public BaseAdapter(_manager) { strategy = _strategy; methodology = _methodology; execution = _execution; incentive = _incentive; _validateSettings(methodology, execution, incentive); } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Engage to target leverage ratio for the first time. SetToken will borrow debt position from Compound and trade for collateral asset. If target * leverage ratio is above max borrow or max trade size, then TWAP is kicked off. To complete engage if TWAP, any valid caller must call iterateRebalance until target * is met. */ function engage() external onlyOperator { ActionInfo memory engageInfo = _createActionInfo(); require(engageInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(engageInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(engageInfo.borrowBalance == 0, "Debt must be 0"); LeverageInfo memory leverageInfo = LeverageInfo({ action: engageInfo, currentLeverageRatio: PreciseUnitMath.preciseUnit(), // 1x leverage in precise units slippageTolerance: execution.slippageTolerance, twapMaxTradeSize: execution.twapMaxTradeSize }); // Calculate total rebalance units and kick off TWAP if above max borrow or max trade size ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.targetLeverageRatio, true); _lever(leverageInfo, chunkRebalanceNotional); _updateRebalanceState( chunkRebalanceNotional, totalRebalanceNotional, methodology.targetLeverageRatio ); emit Engaged( leverageInfo.currentLeverageRatio, methodology.targetLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA AND ALLOWED CALLER: Rebalance according to flexible leverage methodology. If current leverage ratio is between the max and min bounds, then rebalance * can only be called once the rebalance interval has elapsed since last timestamp. If outside the max and min, rebalance can be called anytime to bring leverage * ratio back to the max or min bounds. The methodology will determine whether to delever or lever. * * Note: If the calculated current leverage ratio is above the incentivized leverage ratio or in TWAP then rebalance cannot be called. Instead, you must call * ripcord() which is incentivized with a reward in Ether or iterateRebalance(). */ function rebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, methodology.rebalanceInterval); _validateNonTWAP(); uint256 newLeverageRatio = _calculateNewLeverageRatio(leverageInfo.currentLeverageRatio); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _handleRebalance(leverageInfo, newLeverageRatio); _updateRebalanceState(chunkRebalanceNotional, totalRebalanceNotional, newLeverageRatio); emit Rebalanced( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA AND ALLOWED CALLER: Iterate a rebalance when in TWAP. TWAP cooldown period must have elapsed. If price moves advantageously, then exit without rebalancing * and clear TWAP state. This function can only be called when below incentivized leverage ratio and in TWAP state. */ function iterateRebalance() external onlyEOA onlyAllowedCaller(msg.sender) { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); _validateNormalRebalance(leverageInfo, execution.twapCooldownPeriod); _validateTWAP(); uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (!_isAdvantageousTWAP(leverageInfo.currentLeverageRatio)) { (chunkRebalanceNotional, totalRebalanceNotional) = _handleRebalance(leverageInfo, twapLeverageRatio); } // If not advantageous, then rebalance is skipped and chunk and total rebalance notional are both 0, which means TWAP state is // cleared _updateIterateState(chunkRebalanceNotional, totalRebalanceNotional); emit RebalanceIterated( leverageInfo.currentLeverageRatio, twapLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * ONLY EOA: In case the current leverage ratio exceeds the incentivized leverage threshold, the ripcord function can be called by anyone to return leverage ratio * back to the max leverage ratio. This function typically would only be called during times of high downside volatility and / or normal keeper malfunctions. The caller * of ripcord() will receive a reward in Ether. The ripcord function uses it's own TWAP cooldown period, slippage tolerance and TWAP max trade size which are typically * looser than in regular rebalances. */ function ripcord() external onlyEOA { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo( incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapMaxTradeSize ); _validateRipcord(leverageInfo); ( uint256 chunkRebalanceNotional, ) = _calculateChunkRebalanceNotional(leverageInfo, methodology.maxLeverageRatio, false); _delever(leverageInfo, chunkRebalanceNotional); _updateRipcordState(); uint256 etherTransferred = _transferEtherRewardToCaller(incentive.etherReward); emit RipcordCalled( leverageInfo.currentLeverageRatio, methodology.maxLeverageRatio, chunkRebalanceNotional, etherTransferred ); } /** * OPERATOR ONLY: Return leverage ratio to 1x and delever to repay loan. This can be used for upgrading or shutting down the strategy. SetToken will redeem * collateral position and trade for debt position to repay Compound. If the chunk rebalance size is less than the total notional size, then this function will * delever and repay entire borrow balance on Compound. If chunk rebalance size is above max borrow or max trade size, then operator must * continue to call this function to complete repayment of loan. The function iterateRebalance will not work. * * Note: Delever to 0 will likely result in additional units of the borrow asset added as equity on the SetToken due to oracle price / market price mismatch */ function disengage() external onlyOperator { LeverageInfo memory leverageInfo = _getAndValidateLeveragedInfo(execution.slippageTolerance, execution.twapMaxTradeSize); uint256 newLeverageRatio = PreciseUnitMath.preciseUnit(); ( uint256 chunkRebalanceNotional, uint256 totalRebalanceNotional ) = _calculateChunkRebalanceNotional(leverageInfo, newLeverageRatio, false); if (totalRebalanceNotional > chunkRebalanceNotional) { _delever(leverageInfo, chunkRebalanceNotional); } else { _deleverToZeroBorrowBalance(leverageInfo, totalRebalanceNotional); } emit Disengaged( leverageInfo.currentLeverageRatio, newLeverageRatio, chunkRebalanceNotional, totalRebalanceNotional ); } /** * OPERATOR ONLY: Set methodology settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newMethodologySettings Struct containing methodology parameters */ function setMethodologySettings(MethodologySettings memory _newMethodologySettings) external onlyOperator noRebalanceInProgress { methodology = _newMethodologySettings; _validateSettings(methodology, execution, incentive); emit MethodologySettingsUpdated( methodology.targetLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio, methodology.recenteringSpeed, methodology.rebalanceInterval ); } /** * OPERATOR ONLY: Set execution settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newExecutionSettings Struct containing execution parameters */ function setExecutionSettings(ExecutionSettings memory _newExecutionSettings) external onlyOperator noRebalanceInProgress { execution = _newExecutionSettings; _validateSettings(methodology, execution, incentive); emit ExecutionSettingsUpdated( execution.unutilizedLeveragePercentage, execution.twapMaxTradeSize, execution.twapCooldownPeriod, execution.slippageTolerance, execution.exchangeName, execution.leverExchangeData, execution.deleverExchangeData ); } /** * OPERATOR ONLY: Set incentive settings and check new settings are valid. Note: Need to pass in existing parameters if only changing a few settings. Must not be * in a rebalance. * * @param _newIncentiveSettings Struct containing incentive parameters */ function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress { incentive = _newIncentiveSettings; _validateSettings(methodology, execution, incentive); emit IncentiveSettingsUpdated( incentive.etherReward, incentive.incentivizedLeverageRatio, incentive.incentivizedSlippageTolerance, incentive.incentivizedTwapCooldownPeriod, incentive.incentivizedTwapMaxTradeSize ); } /** * OPERATOR ONLY: Withdraw entire balance of ETH in this contract to operator. Rebalance must not be in progress */ function withdrawEtherBalance() external onlyOperator noRebalanceInProgress { msg.sender.transfer(address(this).balance); } receive() external payable {} /* ============ External Getter Functions ============ */ /** * Get current leverage ratio. Current leverage ratio is defined as the USD value of the collateral divided by the USD value of the SetToken. Prices for collateral * and borrow asset are retrieved from the Compound Price Oracle. * * return currentLeverageRatio Current leverage ratio in precise units (10e18) */ function getCurrentLeverageRatio() public view returns(uint256) { ActionInfo memory currentLeverageInfo = _createActionInfo(); return _calculateCurrentLeverageRatio(currentLeverageInfo.collateralValue, currentLeverageInfo.borrowValue); } /** * Get current Ether incentive for when current leverage ratio exceeds incentivized leverage ratio and ripcord can be called. If ETH balance on the contract is * below the etherReward, then return the balance of ETH instead. * * return etherReward Quantity of ETH reward in base units (10e18) */ function getCurrentEtherIncentive() external view returns(uint256) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); if (currentLeverageRatio >= incentive.incentivizedLeverageRatio) { // If ETH reward is below the balance on this contract, then return ETH balance on contract instead return incentive.etherReward < address(this).balance ? incentive.etherReward : address(this).balance; } else { return 0; } } /** * Helper that checks if conditions are met for rebalance or ripcord. Returns an enum with 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance() * 3 = call ripcord() * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function shouldRebalance() external view returns(ShouldRebalance) { uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, methodology.minLeverageRatio, methodology.maxLeverageRatio); } /** * Helper that checks if conditions are met for rebalance or ripcord with custom max and min bounds specified by caller. This function simplifies the * logic for off-chain keeper bots to determine what threshold to call rebalance when leverage exceeds max or drops below min. Returns an enum with * 0 = no rebalance, 1 = call rebalance(), 2 = call iterateRebalance()3 = call ripcord() * * @param _customMinLeverageRatio Min leverage ratio passed in by caller * @param _customMaxLeverageRatio Max leverage ratio passed in by caller * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(ShouldRebalance) { require ( _customMinLeverageRatio <= methodology.minLeverageRatio && _customMaxLeverageRatio >= methodology.maxLeverageRatio, "Custom bounds must be valid" ); uint256 currentLeverageRatio = getCurrentLeverageRatio(); return _shouldRebalance(currentLeverageRatio, _customMinLeverageRatio, _customMaxLeverageRatio); } /** * Explicit getter functions for parameter structs are defined as workaround to issues fetching structs that have dynamic types. */ function getStrategy() external view returns (ContractSettings memory) { return strategy; } function getMethodology() external view returns (MethodologySettings memory) { return methodology; } function getExecution() external view returns (ExecutionSettings memory) { return execution; } function getIncentive() external view returns (IncentiveSettings memory) { return incentive; } /* ============ Internal Functions ============ */ /** * Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on CompoundLeverageModule * */ function _lever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action); uint256 minReceiveCollateralUnits = _calculateMinCollateralReceiveUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance); bytes memory leverCallData = abi.encodeWithSignature( "lever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.borrowAsset, strategy.collateralAsset, borrowUnits, minReceiveCollateralUnits, execution.exchangeName, execution.leverExchangeData ); invokeManager(address(strategy.leverageModule), leverCallData); } /** * Calculate delever units Invoke delever on CompoundLeverageModule. */ function _delever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 minRepayUnits = _calculateMinRepayUnits(collateralRebalanceUnits, _leverageInfo.slippageTolerance, _leverageInfo.action); bytes memory deleverCallData = abi.encodeWithSignature( "delever(address,address,address,uint256,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, collateralRebalanceUnits, minRepayUnits, execution.exchangeName, execution.deleverExchangeData ); invokeManager(address(strategy.leverageModule), deleverCallData); } /** * Invoke deleverToZeroBorrowBalance on CompoundLeverageModule. */ function _deleverToZeroBorrowBalance( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { // Account for slippage tolerance in redeem quantity for the deleverToZeroBorrowBalance function uint256 maxCollateralRebalanceUnits = _chunkRebalanceNotional .preciseMul(PreciseUnitMath.preciseUnit().add(execution.slippageTolerance)) .preciseDiv(_leverageInfo.action.setTotalSupply); bytes memory deleverToZeroBorrowBalanceCallData = abi.encodeWithSignature( "deleverToZeroBorrowBalance(address,address,address,uint256,string,bytes)", address(strategy.setToken), strategy.collateralAsset, strategy.borrowAsset, maxCollateralRebalanceUnits, execution.exchangeName, execution.deleverExchangeData ); invokeManager(address(strategy.leverageModule), deleverToZeroBorrowBalanceCallData); } /** * Check whether to delever or lever based on the current vs new leverage ratios. Used in the rebalance() and iterateRebalance() functions * * return uint256 Calculated notional to trade * return uint256 Total notional to rebalance over TWAP */ function _handleRebalance(LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio) internal returns(uint256, uint256) { uint256 chunkRebalanceNotional; uint256 totalRebalanceNotional; if (_newLeverageRatio < _leverageInfo.currentLeverageRatio) { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, false); _delever(_leverageInfo, chunkRebalanceNotional); } else { ( chunkRebalanceNotional, totalRebalanceNotional ) = _calculateChunkRebalanceNotional(_leverageInfo, _newLeverageRatio, true); _lever(_leverageInfo, chunkRebalanceNotional); } return (chunkRebalanceNotional, totalRebalanceNotional); } /** * Create the leverage info struct to be used in internal functions * * return LeverageInfo Struct containing ActionInfo and other data */ function _getAndValidateLeveragedInfo(uint256 _slippageTolerance, uint256 _maxTradeSize) internal view returns(LeverageInfo memory) { ActionInfo memory actionInfo = _createActionInfo(); require(actionInfo.setTotalSupply > 0, "SetToken must have > 0 supply"); require(actionInfo.collateralBalance > 0, "Collateral balance must be > 0"); require(actionInfo.borrowBalance > 0, "Borrow balance must exist"); // Get current leverage ratio uint256 currentLeverageRatio = _calculateCurrentLeverageRatio( actionInfo.collateralValue, actionInfo.borrowValue ); return LeverageInfo({ action: actionInfo, currentLeverageRatio: currentLeverageRatio, slippageTolerance: _slippageTolerance, twapMaxTradeSize: _maxTradeSize }); } /** * Create the action info struct to be used in internal functions * * return ActionInfo Struct containing data used by internal lever and delever functions */ function _createActionInfo() internal view returns(ActionInfo memory) { ActionInfo memory rebalanceInfo; // IMPORTANT: Compound oracle returns prices adjusted for decimals. USDC is 6 decimals so $1 * 10^18 * 10^18 / 10^6 = 10^30 rebalanceInfo.collateralPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetCollateralCToken)); rebalanceInfo.borrowPrice = strategy.priceOracle.getUnderlyingPrice(address(strategy.targetBorrowCToken)); // Calculate stored exchange rate which does not trigger a state update uint256 cTokenBalance = strategy.targetCollateralCToken.balanceOf(address(strategy.setToken)); rebalanceInfo.collateralBalance = cTokenBalance.preciseMul(strategy.targetCollateralCToken.exchangeRateStored()); rebalanceInfo.borrowBalance = strategy.targetBorrowCToken.borrowBalanceStored(address(strategy.setToken)); rebalanceInfo.collateralValue = rebalanceInfo.collateralPrice.preciseMul(rebalanceInfo.collateralBalance); rebalanceInfo.borrowValue = rebalanceInfo.borrowPrice.preciseMul(rebalanceInfo.borrowBalance); rebalanceInfo.setTotalSupply = strategy.setToken.totalSupply(); return rebalanceInfo; } /** * Validate settings in constructor and setters when updating. */ function _validateSettings( MethodologySettings memory _methodology, ExecutionSettings memory _execution, IncentiveSettings memory _incentive ) internal pure { require ( _methodology.minLeverageRatio <= _methodology.targetLeverageRatio && _methodology.minLeverageRatio > 0, "Must be valid min leverage" ); require ( _methodology.maxLeverageRatio >= _methodology.targetLeverageRatio, "Must be valid max leverage" ); require ( _methodology.recenteringSpeed <= PreciseUnitMath.preciseUnit() && _methodology.recenteringSpeed > 0, "Must be valid recentering speed" ); require ( _execution.unutilizedLeveragePercentage <= PreciseUnitMath.preciseUnit(), "Unutilized leverage must be <100%" ); require ( _execution.slippageTolerance <= PreciseUnitMath.preciseUnit(), "Slippage tolerance must be <100%" ); require ( _incentive.incentivizedSlippageTolerance <= PreciseUnitMath.preciseUnit(), "Incentivized slippage tolerance must be <100%" ); require ( _incentive.incentivizedLeverageRatio >= _methodology.maxLeverageRatio, "Incentivized leverage ratio must be > max leverage ratio" ); require ( _methodology.rebalanceInterval >= _execution.twapCooldownPeriod, "Rebalance interval must be greater than TWAP cooldown period" ); require ( _execution.twapCooldownPeriod >= _incentive.incentivizedTwapCooldownPeriod, "TWAP cooldown must be greater than incentivized TWAP cooldown" ); require ( _execution.twapMaxTradeSize <= _incentive.incentivizedTwapMaxTradeSize, "TWAP max trade size must be less than incentivized TWAP max trade size" ); } /** * Validate that current leverage is below incentivized leverage ratio and cooldown / rebalance period has elapsed or outsize max/min bounds. Used * in rebalance() and iterateRebalance() functions */ function _validateNormalRebalance(LeverageInfo memory _leverageInfo, uint256 _coolDown) internal view { require(_leverageInfo.currentLeverageRatio < incentive.incentivizedLeverageRatio, "Must be below incentivized leverage ratio"); require( block.timestamp.sub(lastTradeTimestamp) > _coolDown || _leverageInfo.currentLeverageRatio > methodology.maxLeverageRatio || _leverageInfo.currentLeverageRatio < methodology.minLeverageRatio, "Cooldown not elapsed or not valid leverage ratio" ); } /** * Validate that current leverage is above incentivized leverage ratio and incentivized cooldown period has elapsed in ripcord() */ function _validateRipcord(LeverageInfo memory _leverageInfo) internal view { require(_leverageInfo.currentLeverageRatio >= incentive.incentivizedLeverageRatio, "Must be above incentivized leverage ratio"); // If currently in the midst of a TWAP rebalance, ensure that the cooldown period has elapsed require(lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp, "TWAP cooldown must have elapsed"); } /** * Validate TWAP in the iterateRebalance() function */ function _validateTWAP() internal view { require(twapLeverageRatio > 0, "Not in TWAP state"); } /** * Validate not TWAP in the rebalance() function */ function _validateNonTWAP() internal view { require(twapLeverageRatio == 0, "Must call iterate"); } /** * Check if price has moved advantageously while in the midst of the TWAP rebalance. This means the current leverage ratio has moved over/under * the stored TWAP leverage ratio on lever/delever so there is no need to execute a rebalance. Used in iterateRebalance() */ function _isAdvantageousTWAP(uint256 _currentLeverageRatio) internal view returns (bool) { return ( (twapLeverageRatio < methodology.targetLeverageRatio && _currentLeverageRatio >= twapLeverageRatio) || (twapLeverageRatio > methodology.targetLeverageRatio && _currentLeverageRatio <= twapLeverageRatio) ); } /** * Calculate the current leverage ratio given a valuation of the collateral and borrow asset, which is calculated as collateral USD valuation / SetToken USD valuation * * return uint256 Current leverage ratio */ function _calculateCurrentLeverageRatio( uint256 _collateralValue, uint256 _borrowValue ) internal pure returns(uint256) { return _collateralValue.preciseDiv(_collateralValue.sub(_borrowValue)); } /** * Calculate the new leverage ratio using the flexible leverage methodology. The methodology reduces the size of each rebalance by weighting * the current leverage ratio against the target leverage ratio by the recentering speed percentage. The lower the recentering speed, the slower * the leverage token will move towards the target leverage each rebalance. * * return uint256 New leverage ratio based on the flexible leverage methodology */ function _calculateNewLeverageRatio(uint256 _currentLeverageRatio) internal view returns(uint256) { // CLRt+1 = max(MINLR, min(MAXLR, CLRt * (1 - RS) + TLR * RS)) // a: TLR * RS // b: (1- RS) * CLRt // c: (1- RS) * CLRt + TLR * RS // d: min(MAXLR, CLRt * (1 - RS) + TLR * RS) uint256 a = methodology.targetLeverageRatio.preciseMul(methodology.recenteringSpeed); uint256 b = PreciseUnitMath.preciseUnit().sub(methodology.recenteringSpeed).preciseMul(_currentLeverageRatio); uint256 c = a.add(b); uint256 d = Math.min(c, methodology.maxLeverageRatio); return Math.max(methodology.minLeverageRatio, d); } /** * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units. * * return uint256 Chunked rebalance notional in collateral units * return uint256 Total rebalance notional in collateral units */ function _calculateChunkRebalanceNotional( LeverageInfo memory _leverageInfo, uint256 _newLeverageRatio, bool _isLever ) internal view returns (uint256, uint256) { // Calculate absolute value of difference between new and current leverage ratio uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio); uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance); uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever); uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize); return (chunkRebalanceNotional, totalRebalanceNotional); } /** * Calculate the max borrow / repay amount allowed in collateral units for lever / delever. This is due to overcollateralization requirements on * assets deposited in lending protocols for borrowing. * * For lever, max borrow is calculated as: * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals * * For delever, max borrow is calculated as: * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD * * Net borrow limit is calculated as: * The collateral value in USD * Compound collateral factor * (1 - unutilized leverage %) * * return uint256 Max borrow notional denominated in collateral asset */ function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) { // Retrieve collateral factor which is the % increase in borrow limit in precise units (75% = 75 * 1e16) ( , uint256 collateralFactorMantissa, ) = strategy.comptroller.markets(address(strategy.targetCollateralCToken)); uint256 netBorrowLimit = _actionInfo.collateralValue .preciseMul(collateralFactorMantissa) .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage)); if (_isLever) { return netBorrowLimit .sub(_actionInfo.borrowValue) .preciseDiv(_actionInfo.collateralPrice); } else { return _actionInfo.collateralBalance .preciseMul(netBorrowLimit.sub(_actionInfo.borrowValue)) .preciseDiv(netBorrowLimit); } } /** * Derive the borrow units for lever. The units are calculated by the collateral units multiplied by collateral / borrow asset price. Compound oracle prices * already adjust for decimals in the token. * * return uint256 Position units to borrow */ function _calculateBorrowUnits(uint256 _collateralRebalanceUnits, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(_actionInfo.collateralPrice).preciseDiv(_actionInfo.borrowPrice); } /** * Calculate the min receive units in collateral units for lever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance * * return uint256 Min position units to receive after lever trade */ function _calculateMinCollateralReceiveUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance) internal pure returns (uint256) { return _collateralRebalanceUnits.preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } /** * Derive the min repay units from collateral units for delever. Units are calculated as target collateral rebalance units multiplied by slippage tolerance * and pair price (collateral oracle price / borrow oracle price). Compound oracle prices already adjust for decimals in the token. * * return uint256 Min position units to repay in borrow asset */ function _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) { return _collateralRebalanceUnits .preciseMul(_actionInfo.collateralPrice) .preciseDiv(_actionInfo.borrowPrice) .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance)); } /** * Update last trade timestamp and if chunk rebalance size is less than total rebalance notional, store new leverage ratio to kick off TWAP. Used in * the engage() and rebalance() functions */ function _updateRebalanceState( uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional, uint256 _newLeverageRatio ) internal { lastTradeTimestamp = block.timestamp; if (_chunkRebalanceNotional < _totalRebalanceNotional) { twapLeverageRatio = _newLeverageRatio; } } /** * Update last trade timestamp and if chunk rebalance size is equal to the total rebalance notional, end TWAP by clearing state. This function is used * in iterateRebalance() */ function _updateIterateState(uint256 _chunkRebalanceNotional, uint256 _totalRebalanceNotional) internal { lastTradeTimestamp = block.timestamp; // If the chunk size is equal to the total notional meaning that rebalances are not chunked, then clear TWAP state. if (_chunkRebalanceNotional == _totalRebalanceNotional) { delete twapLeverageRatio; } } /** * Update last trade timestamp and if currently in a TWAP, delete the TWAP state. Used in the ripcord() function. */ function _updateRipcordState() internal { lastTradeTimestamp = block.timestamp; // If TWAP leverage ratio is stored, then clear state. This may happen if we are currently in a TWAP rebalance, and the leverage ratio moves above the // incentivized threshold for ripcord. if (twapLeverageRatio > 0) { delete twapLeverageRatio; } } /** * Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required * incentive quantity, then transfer contract balance instead to prevent reverts. * * return uint256 Amount of ETH transferred to caller */ function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) { uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance; msg.sender.transfer(etherToTransfer); return etherToTransfer; } /** * Internal function returning the ShouldRebalance enum used in shouldRebalance and shouldRebalanceWithBounds external getter functions * * return ShouldRebalance Enum detailing whether to rebalance, iterateRebalance, ripcord or no action */ function _shouldRebalance( uint256 _currentLeverageRatio, uint256 _minLeverageRatio, uint256 _maxLeverageRatio ) internal view returns(ShouldRebalance) { // If above ripcord threshold, then check if incentivized cooldown period has elapsed if (_currentLeverageRatio >= incentive.incentivizedLeverageRatio) { if (lastTradeTimestamp.add(incentive.incentivizedTwapCooldownPeriod) < block.timestamp) { return ShouldRebalance.RIPCORD; } } else { // If TWAP, then check if the cooldown period has elapsed if (twapLeverageRatio > 0) { if (lastTradeTimestamp.add(execution.twapCooldownPeriod) < block.timestamp) { return ShouldRebalance.ITERATE_REBALANCE; } } else { // If not TWAP, then check if the rebalance interval has elapsed OR current leverage is above max leverage OR current leverage is below // min leverage if ( block.timestamp.sub(lastTradeTimestamp) > methodology.rebalanceInterval || _currentLeverageRatio > _maxLeverageRatio || _currentLeverageRatio < _minLeverageRatio ) { return ShouldRebalance.REBALANCE; } } } // If none of the above conditions are satisfied, then should not rebalance return ShouldRebalance.NONE; } } pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ICErc20 * * Interface for interacting with Compound cErc20 tokens (e.g. Dai, USDC) */ interface ICErc20 is IERC20 { function borrowBalanceCurrent(address _account) external returns (uint256); function borrowBalanceStored(address _account) external view returns (uint256); function balanceOfUnderlying(address _account) external returns (uint256); /** * Calculates the exchange rate from the underlying to the CToken * * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external view returns (address); /** * Sender supplies assets into the market and receives cTokens in exchange * * @notice Accrues interest whether or not the operation succeeds, unless reverted * @param _mintAmount The amount of the underlying asset to supply * @return uint256 0=success, otherwise a failure */ function mint(uint256 _mintAmount) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param _redeemTokens The number of cTokens to redeem into underlying * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 _redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param _redeemAmount The amount of underlying to redeem * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 _redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param _borrowAmount The amount of the underlying asset to borrow * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 _borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @param _repayAmount The amount to repay * @return uint256 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 _repayAmount) external returns (uint256); } pragma solidity 0.6.10; /** * @title ICompoundPriceOracle * * Interface for interacting with Compound price oracle */ interface ICompoundPriceOracle { function getUnderlyingPrice(address _asset) external view returns(uint256); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { FlexibleLeverageStrategyAdapter } from "../adapters/FlexibleLeverageStrategyAdapter.sol"; interface IFLIStrategyAdapter { function getStrategy() external view returns (FlexibleLeverageStrategyAdapter.ContractSettings memory); function getMethodology() external view returns (FlexibleLeverageStrategyAdapter.MethodologySettings memory); function getIncentive() external view returns (FlexibleLeverageStrategyAdapter.IncentiveSettings memory); function getExecution() external view returns (FlexibleLeverageStrategyAdapter.ExecutionSettings memory); function getCurrentLeverageRatio() external view returns (uint256); function shouldRebalance() external view returns (FlexibleLeverageStrategyAdapter.ShouldRebalance); function shouldRebalanceWithBounds( uint256 _customMinLeverageRatio, uint256 _customMaxLeverageRatio ) external view returns(FlexibleLeverageStrategyAdapter.ShouldRebalance); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IUniswapV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol"; import { IBaseManager } from "../interfaces/IBaseManager.sol"; /** * @title BaseAdapter * @author Set Protocol * * Abstract class that houses common adapter-related state and functions. */ abstract contract BaseAdapter { using AddressArrayUtils for address[]; /* ============ Events ============ */ event CallerStatusUpdated(address indexed _caller, bool _status); event AnyoneCallableUpdated(bool indexed _status); /* ============ Modifiers ============ */ /** * Throws if the sender is not the SetToken operator */ modifier onlyOperator() { require(msg.sender == manager.operator(), "Must be operator"); _; } /** * Throws if the sender is not the SetToken methodologist */ modifier onlyMethodologist() { require(msg.sender == manager.methodologist(), "Must be methodologist"); _; } /** * Throws if caller is a contract, can be used to stop flash loan and sandwich attacks */ modifier onlyEOA() { require(msg.sender == tx.origin, "Caller must be EOA Address"); _; } /** * Throws if not allowed caller */ modifier onlyAllowedCaller(address _caller) { require(isAllowedCaller(_caller), "Address not permitted to call"); _; } /* ============ State Variables ============ */ // Instance of manager contract IBaseManager public manager; // Boolean indicating if anyone can call function bool public anyoneCallable; // Mapping of addresses allowed to call function mapping(address => bool) public callAllowList; /* ============ Constructor ============ */ constructor(IBaseManager _manager) public { manager = _manager; } /* ============ External Functions ============ */ /** * OPERATOR ONLY: Toggle ability for passed addresses to call only allowed caller functions * * @param _callers Array of caller addresses to toggle status * @param _statuses Array of statuses for each caller */ function updateCallerStatus(address[] calldata _callers, bool[] calldata _statuses) external onlyOperator { require(_callers.length == _statuses.length, "Array length mismatch"); require(_callers.length > 0, "Array length must be > 0"); require(!_callers.hasDuplicate(), "Cannot duplicate callers"); for (uint256 i = 0; i < _callers.length; i++) { address caller = _callers[i]; bool status = _statuses[i]; callAllowList[caller] = status; emit CallerStatusUpdated(caller, status); } } /** * OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist * * @param _status Boolean indicating whether to allow anyone call */ function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); } /* ============ Internal Functions ============ */ /** * Invoke manager to transfer tokens from manager to other contract. * * @param _token Token being transferred from manager contract * @param _amount Amount of token being transferred */ function invokeManagerTransfer(address _token, address _destination, uint256 _amount) internal { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _destination, _amount); invokeManager(_token, callData); } /** * Invoke call from manager * * @param _module Module to interact with * @param _encoded Encoded byte data */ function invokeManager(address _module, bytes memory _encoded) internal { manager.interactManager(_module, _encoded); } /** * Determine if passed address is allowed to call function. If anyoneCallable set to true anyone can call otherwise needs to be approved. * * return bool Boolean indicating if allowed caller */ function isAllowedCaller(address _caller) internal view virtual returns (bool) { return anyoneCallable || callAllowList[_caller]; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface IBaseManager { function setToken() external returns(ISetToken); function methodologist() external returns(address); function operator() external returns(address); function interactManager(address _module, bytes calldata _encoded) external; } pragma solidity 0.6.10; /** * @title IComptroller * * Interface for interacting with Compound Comptroller */ interface IComptroller { /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) external returns (uint256[] memory); /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing neccessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint256); function claimComp(address holder) external; function markets(address cTokenAddress) external view returns (bool, uint256, bool); } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { ISetToken } from "./ISetToken.sol"; interface ICompoundLeverageModule { function sync( ISetToken _setToken ) external; function lever( ISetToken _setToken, address _borrowAsset, address _collateralAsset, uint256 _borrowQuantity, uint256 _minReceiveQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; function delever( ISetToken _setToken, address _collateralAsset, address _repayAsset, uint256 _redeemQuantity, uint256 _minRepayQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; function gulp( ISetToken _setToken, address _collateralAsset, uint256 _minNotionalReceiveQuantity, string memory _tradeAdapterName, bytes memory _tradeData ) external; } pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/27/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
Instance of Compound Comptroller
IComptroller comptroller;
478,695
[ 1, 1442, 434, 21327, 1286, 337, 1539, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 799, 337, 1539, 532, 337, 1539, 31, 7682, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42161/0x8516c8Af8397F319686E5946837aaBC5D922b4ab/sources/project_/contracts/current/CasinoTreasury.sol
* Function modifier to require caller to be a whitelisted contract/
modifier onlyCasino() { require(casinoContracts[msg.sender], "Only casino contracts can call this function"); _; }
16,299,330
[ 1, 2083, 9606, 358, 2583, 4894, 358, 506, 279, 26944, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 39, 345, 15020, 1435, 288, 203, 3639, 2583, 12, 6349, 15020, 20723, 63, 3576, 18, 15330, 6487, 315, 3386, 8697, 15020, 20092, 848, 745, 333, 445, 8863, 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 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./IOwnableUpgradeable.sol"; /// @title OwnableUpgradeable /// @author Hifi /// @dev Forked from OpenZeppelin /// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol contract OwnableUpgradeable is IOwnableUpgradeable, // no dependency Initializable // no dependency { /// PUBLIC STORAGE /// /// @inheritdoc IOwnableUpgradeable address public override owner; /// MODIFIERS /// /// @notice Throws if called by any account other than the owner. modifier onlyOwner() { if (owner != msg.sender) { revert OwnableUpgradeable__NotOwner(owner, msg.sender); } _; } /// INITIALIZER /// /// @notice The upgradeability variant of the contract constructor. /// @dev Sets the deployer as the initial owner. function __Ownable_init() internal onlyInitializing { owner = msg.sender; emit TransferOwnership(address(0), msg.sender); } /// PUBLIC NON-CONSTANT FUNCTIONS /// /// @inheritdoc IOwnableUpgradeable function _renounceOwnership() external virtual override onlyOwner { emit TransferOwnership(owner, address(0)); owner = address(0); } /// @inheritdoc IOwnableUpgradeable function _transferOwnership(address newOwner) external virtual override onlyOwner { if (newOwner == address(0)) { revert OwnableUpgradeable__OwnerZeroAddress(); } emit TransferOwnership(owner, newOwner); owner = newOwner; } }
@notice The upgradeability variant of the contract constructor. @dev Sets the deployer as the initial owner.
function __Ownable_init() internal onlyInitializing { owner = msg.sender; emit TransferOwnership(address(0), msg.sender); }
12,681,088
[ 1, 1986, 8400, 2967, 5437, 434, 326, 6835, 3885, 18, 225, 11511, 326, 7286, 264, 487, 326, 2172, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1001, 5460, 429, 67, 2738, 1435, 2713, 1338, 29782, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 12279, 5460, 12565, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; struct Purchase { uint256 buyAmount; uint256 transferredAmount; uint256 purchaseBlock; } mapping(address => uint256) balances; mapping(address => Purchase[]) public presaleInvestors; mapping(address => uint256) public mainSaleInvestors; uint256 totalSupply_; uint256 public secondsPerBlock = 147; // change to 14 uint256 public startLockUpSec = 3888000; // 45 days => 3888000 secs uint256 public secondsPerMonth = 2592000; // 30 days => 2592000 secs uint256 public percentagePerMonth = 10; function _checkLockUp(address senderAdr) public view returns (uint) { uint canTransfer = 0; if (presaleInvestors[senderAdr].length == 0) { canTransfer = 0; } else if (presaleInvestors[senderAdr][0].purchaseBlock > block.number.sub(startLockUpSec.div(secondsPerBlock).mul(10))) { canTransfer = 0; } else { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } uint actAmount = (presaleInvestors[senderAdr][i].buyAmount).mul(months).mul(percentagePerMonth).div(100); uint realAmout = actAmount.sub(presaleInvestors[senderAdr][i].transferredAmount); canTransfer = canTransfer.add(realAmout); } else { break; } } } return canTransfer.add(mainSaleInvestors[senderAdr]); } function cleanTokensAmount(address senderAdr, uint256 currentTokens) public returns (bool) { if (presaleInvestors[senderAdr].length != 0) { for (uint i = 0; i < presaleInvestors[senderAdr].length; i++) { if (presaleInvestors[senderAdr][i].transferredAmount == presaleInvestors[senderAdr][i].buyAmount) { continue; } if (presaleInvestors[senderAdr][i].purchaseBlock <= (block.number).sub(startLockUpSec.div(secondsPerBlock).mul(10))) { uint months = (block.number.sub(presaleInvestors[senderAdr][i].purchaseBlock)).div(secondsPerMonth); if (months > 10) { months = 10; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) >= currentTokens) { presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].transferredAmount + currentTokens; currentTokens = 0; } if ((presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount) < currentTokens) { uint remainder = currentTokens - (presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth) - presaleInvestors[senderAdr][i].transferredAmount); presaleInvestors[senderAdr][i].transferredAmount = presaleInvestors[senderAdr][i].buyAmount.div(100).mul(months).mul(percentagePerMonth); currentTokens = remainder; } } else { continue; } } if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; } else { revert(); } } else { if (currentTokens <= mainSaleInvestors[senderAdr]) { mainSaleInvestors[senderAdr] = mainSaleInvestors[senderAdr] - currentTokens; currentTokens = 0; } else { revert(); } } if (currentTokens != 0) { revert(); } } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0); require(_value <= balances[msg.sender]); require(_checkLockUp(msg.sender) >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); cleanTokensAmount(msg.sender, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure require(_checkLockUp(_who) >= _value); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); cleanTokensAmount(_who, _value); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BurnableToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value > 0); require(_value <= allowed[_from][msg.sender]); require(_checkLockUp(_from) >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); cleanTokensAmount(_from, _value); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_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&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); mainSaleInvestors[_to] = mainSaleInvestors[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract WiredToken is MintableToken { string public constant name = "Wired Token"; string public constant symbol = "WRD"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 410000000000000000000; // 10^28 address public agent; uint256 public distributeAmount = 41000000000000000000; uint256 public mulbonus = 1000; uint256 public divbonus = 10000000000; bool public presalePart = true; modifier onlyAgent() { require(msg.sender == owner || msg.sender == agent); _; } function WiredToken() public { totalSupply_ = INITIAL_SUPPLY; balances[address(this)] = INITIAL_SUPPLY; mainSaleInvestors[address(this)] = INITIAL_SUPPLY; agent = msg.sender; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint256 amount) external onlyAgent { require(amount > 0 && addresses.length > 0); uint256 amounts = amount.mul(100000000); uint256 totalAmount = amounts.mul(addresses.length); require(balances[address(this)] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != 0x0); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); mainSaleInvestors[addresses[i]] = mainSaleInvestors[addresses[i]].add(amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function distributeAirdropMulti(address[] addresses, uint256[] amount) external onlyAgent { require(addresses.length > 0 && addresses.length == amount.length); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++) { require(amount[i] > 0 && addresses[i] != 0x0); uint256 amounts = amount[i].mul(100000000); totalAmount = totalAmount.add(amounts); require(balances[address(this)] >= totalAmount); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); mainSaleInvestors[addresses[i]] = mainSaleInvestors[addresses[i]].add(amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function distributeAirdropMultiPresale(address[] addresses, uint256[] amount, uint256[] blocks) external onlyAgent { require(addresses.length > 0 && addresses.length == amount.length); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++) { require(amount[i] > 0 && addresses[i] != 0x0); uint256 amounts = amount[i].mul(100000000); totalAmount = totalAmount.add(amounts); require(balances[address(this)] >= totalAmount); presaleInvestors[addresses[i]].push(Purchase(amounts, 0, blocks[i])); balances[addresses[i]] = balances[addresses[i]].add(amounts); emit Transfer(address(this), addresses[i], amounts); } balances[address(this)] = balances[address(this)].sub(totalAmount); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(totalAmount); } function setDistributeAmount(uint256 _unitAmount) onlyOwner external { distributeAmount = _unitAmount; } function setMulBonus(uint256 _mulbonus) onlyOwner external { mulbonus = _mulbonus; } function setDivBonus(uint256 _divbonus) onlyOwner external { divbonus = _divbonus; } function setNewAgent(address _agent) external onlyOwner { require(agent != address(0)); agent = _agent; } function changeTime(uint256 _time) external onlyOwner { secondsPerBlock = _time; } function transferFund() external onlyOwner { owner.transfer(address(this).balance); } function transferTokens(uint256 amount) external onlyOwner { require(balances[address(this)] > 0); balances[msg.sender] = balances[msg.sender].add(amount.mul(100000000)); balances[address(this)] = balances[address(this)].sub(amount.mul(100000000)); emit Transfer(address(this), msg.sender, balances[address(this)]); mainSaleInvestors[msg.sender] = mainSaleInvestors[msg.sender].add(amount.mul(100000000)); mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(amount.mul(100000000)); } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn&#39;t work */ function buy(address buyer) payable public { require(msg.value > 10000000000000 && distributeAmount > 0 && balances[address(this)] > distributeAmount); uint256 amount = msg.value.mul(mulbonus).div(divbonus); balances[buyer] = balances[buyer].add(amount); emit Transfer(address(this), buyer, amount); if (presalePart) { presaleInvestors[buyer].push(Purchase(amount, 0, block.number)); } else { mainSaleInvestors[buyer] = mainSaleInvestors[buyer].add(amount); } mainSaleInvestors[address(this)] = mainSaleInvestors[address(this)].sub(amount); balances[address(this)] = balances[address(this)].sub(amount); distributeAmount = distributeAmount.sub(amount); } /** * @dev fallback function */ function() payable public { buy(msg.sender); } }
* @title Burnable Token @dev Token that can be irreversibly burned (destroyed)./
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); require(_checkLockUp(_who) >= _value); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); cleanTokensAmount(_who, _value); } }
2,370,045
[ 1, 38, 321, 429, 3155, 225, 3155, 716, 848, 506, 9482, 266, 2496, 24755, 18305, 329, 261, 11662, 329, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 321, 429, 1345, 353, 7651, 1345, 288, 203, 203, 225, 871, 605, 321, 12, 2867, 8808, 18305, 264, 16, 2254, 5034, 460, 1769, 203, 203, 225, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 565, 389, 70, 321, 12, 3576, 18, 15330, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 70, 321, 12, 2867, 389, 3350, 83, 16, 2254, 5034, 389, 1132, 13, 2713, 288, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 3350, 83, 19226, 203, 565, 2583, 24899, 1893, 2531, 1211, 24899, 3350, 83, 13, 1545, 389, 1132, 1769, 203, 203, 565, 324, 26488, 63, 67, 3350, 83, 65, 273, 324, 26488, 63, 67, 3350, 83, 8009, 1717, 24899, 1132, 1769, 203, 565, 2078, 3088, 1283, 67, 273, 2078, 3088, 1283, 27799, 1717, 24899, 1132, 1769, 203, 565, 3626, 605, 321, 24899, 3350, 83, 16, 389, 1132, 1769, 203, 565, 3626, 12279, 24899, 3350, 83, 16, 1758, 12, 20, 3631, 389, 1132, 1769, 203, 565, 2721, 5157, 6275, 24899, 3350, 83, 16, 389, 1132, 1769, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./ReentrancyGuard.sol"; import "./PolkaWarItemSystem.sol"; import "./PolkaWar.sol"; import "./CorgibStaking.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract PolkaWarFlashSale is Ownable, ReentrancyGuard { string public name = "PolkaWar: NFT FlashSale"; using SafeMath for uint256; using SafeERC20 for IERC20; PolkaWarItemSystem itemSystem; PolkaWar polkaWar; CorgibStaking staking; address payable private fundOwner; uint256 beginDate; uint256 endDate; uint256 public maximumSoldCount; uint256 public maximumPerItem; uint256 price; uint256 public minimumHolding; uint256 buybackPrice; uint256 resellBeginDate; uint256 resellEndDate; struct Item { uint256 countSlot; bool isValid; } //list airdrop item mapping(address => uint256) internal participants; //user-tokenid (1user can only buy 1 NFT in flashsale) address[] internal arrParticipants; //user-tokenid mapping(uint256 => Item) public listItem; event purchaseEvent(address user, uint256 tokenId, string itemInfoHash); event resellEvent(address user, uint256 tokenId); constructor( PolkaWarItemSystem _itemSystem, PolkaWar _polkaWar, CorgibStaking _staking, address payable _fundOwner ) public { itemSystem = _itemSystem; polkaWar = _polkaWar; staking = _staking; fundOwner = _fundOwner; maximumSoldCount = 200; maximumPerItem = 20; beginDate = 1636207200; endDate = 1636210800; resellBeginDate = 1636214400; resellEndDate = 1636218000; price = 1000000000000000000; minimumHolding = 2000000000000000000000; buybackPrice = 1100000000000000000; } function initItem(uint256[] memory _lstItem) public onlyOwner { for (uint256 i = 0; i < _lstItem.length; i++) { listItem[_lstItem[i]].isValid = true; listItem[_lstItem[i]].countSlot = 0; } } function changeConstant( uint256 _beginDate, uint256 _endDate, uint256 _maximumSoldCount, uint256 _maximumPerItem, uint256 _price, uint256 _buybackprice, uint256 _resellBeginDate, uint256 _resellEndDate, uint256 _minimumHolding ) public onlyOwner { if (_beginDate > 0) { beginDate = _beginDate; } if (_endDate > 0) { endDate = _endDate; } if (_maximumSoldCount > 0) { maximumSoldCount = _maximumSoldCount; } if (_price > 0) { price = _price; } if (_buybackprice > 0) { buybackPrice = _buybackprice; } if (_resellBeginDate > 0) { resellBeginDate = _resellBeginDate; } if (_resellEndDate > 0) { resellEndDate = _resellEndDate; } if (_maximumPerItem > 0) { maximumPerItem = _maximumPerItem; } if (_minimumHolding > 0) { minimumHolding = _minimumHolding; } } function purchaseItem( uint256 itemId, string memory itemInfoHash, uint8 v, bytes32 r, bytes32 s, bytes32 messageHash ) public payable nonReentrant returns (uint256) { require( owner() == ecrecover(messageHash, v, r, s), "owner should sign purchase info" ); require( block.timestamp >= beginDate && block.timestamp <= endDate, "flashsale finished" ); require( getTotalParticipants() <= maximumSoldCount, "reached maximum slots" ); require(listItem[itemId].isValid, "not valid item"); require( listItem[itemId].countSlot < maximumPerItem, "This item is sold out" ); require(msg.value >= price, "invalid price"); require(!isPurchased(msg.sender), "already purchased"); uint256 numberHoldingOrStaking = getNumberHoldingOrStaking(msg.sender); require( numberHoldingOrStaking >= minimumHolding, "Insufficient number of PWAR staking or holding" ); uint256 tokenId = itemSystem.createItem(msg.sender, itemInfoHash); participants[msg.sender] = tokenId; arrParticipants.push(msg.sender); listItem[itemId].countSlot = listItem[itemId].countSlot.add(1); emit purchaseEvent(msg.sender, tokenId, itemInfoHash); return tokenId; } //resell flashsale item for system function resellItemForSystem() public nonReentrant { address payable user = msg.sender; require( block.timestamp >= resellBeginDate, "buyback program not started yet" ); require(block.timestamp <= resellEndDate, "buyback program ended"); require(address(this).balance >= buybackPrice, "not enough fund"); uint256 ownTokenId = participants[user]; require(ownTokenId > 0, "invalid item"); itemSystem.safeTransferFrom(user, owner(), ownTokenId); user.transfer(buybackPrice); emit resellEvent(user, ownTokenId); } function isPurchased(address user) public view returns (bool) { if (participants[user] > 0) return true; return false; } function getTotalParticipants() public view returns (uint256) { return arrParticipants.length; } function getNumberHoldingOrStaking(address user) public view returns (uint256) { uint256 amountHolding = polkaWar.balanceOf(user); ( uint256 amount, uint256 rewardDebt, uint256 rewardClaimed, uint256 lastBlock, uint256 beginTime, uint256 endTime ) = getUserStakingData(user, 1); return amountHolding.add(amount); } function getUserStakingData(address user, uint256 poolId) public view returns ( uint256 amount, uint256 rewardDebt, uint256 rewardClaimed, uint256 lastBlock, uint256 beginTime, uint256 endTime ) { return (staking.userInfo(poolId, user)); } function withdrawToken(IERC20 token) public onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } function withdrawPoolFund() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "not enough fund"); fundOwner.transfer(balance); } receive() external payable {} }
user-tokenid (1user can only buy 1 NFT in flashsale)
mapping(address => uint256) internal participants;
955,916
[ 1, 1355, 17, 2316, 350, 261, 21, 1355, 848, 1338, 30143, 404, 423, 4464, 316, 9563, 87, 5349, 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 ]
[ 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, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 22346, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; /* * @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 returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _authorizedNewOwner; event OwnershipTransferAuthorization(address indexed authorizedAddress); 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 Returns the address of the current authorized new owner. */ function authorizedNewOwner() public view returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner { _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership"); emit OwnershipTransferred(_owner, _authorizedNewOwner); _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); } /** * @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. * * @param confirmAddress The address wants to give up ownership. */ function renounceOwnership(address confirmAddress) public onlyOwner { require(confirmAddress == _owner, "Ownable: confirm address is wrong"); emit OwnershipTransferred(_owner, address(0)); _authorizedNewOwner = address(0); _owner = address(0); } } contract AGL is Ownable { /// @notice BEP-20 token name for this token string public constant name = "Agile"; /// @notice BEP-20 token symbol for this token string public constant symbol = "AGL"; /// @notice BEP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 1000000000e18; // 1 billion AGL /// @notice Reward eligible epochs uint32 public constant eligibleEpochs = 30; // 30 epochs /// @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 transferPoint for marking balance from given epoch struct TransferPoint { uint32 epoch; uint96 balance; } /// @notice A epoch config for blocks or ROI per epoch struct EpochConfig { uint32 epoch; uint32 blocks; uint32 roi; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice A record of transfer checkpoints for each account mapping (address => mapping (uint32 => TransferPoint)) public transferPoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The number of transferPoints for each account mapping (address => uint32) public numTransferPoints; /// @notice The claimed amount for each account mapping (address => uint96) public claimedAmounts; /// @notice Configs for epoch EpochConfig[] public epochConfigs; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @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 An event thats emitted when a transfer point balance changes // event TransferPointChanged(address indexed src, uint srcBalance, address indexed dst, uint dstBalance); /// @notice An event thats emitted when epoch block count changes event EpochConfigChanged(uint32 indexed previousEpoch, uint32 previousBlocks, uint32 previousROI, uint32 indexed newEpoch, uint32 newBlocks, uint32 newROI); /// @notice The standard BEP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard BEP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new AGL token * @param account The initial account to grant all the tokens */ constructor(address account) public { EpochConfig memory newEpochConfig = EpochConfig( 0, 24 * 60 * 60 / 3, // 1 day blocks in BSC 20 // 0.2% ROI increase per epoch ); epochConfigs.push(newEpochConfig); emit EpochConfigChanged(0, 0, 0, newEpochConfig.epoch, newEpochConfig.blocks, newEpochConfig.roi); balances[account] = uint96(totalSupply); _writeTransferPoint(address(0), account, 0, 0, uint96(totalSupply)); emit Transfer(address(0), account, totalSupply); } /** * @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` * @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, "AGL::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @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, "AGL::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, "AGL::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "AGL::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), "AGL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "AGL::delegateBySig: invalid nonce"); require(now <= expiry, "AGL::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, "AGL::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; } /** * @notice Sets block counter per epoch * @param blocks The count of blocks per epoch * @param roi The interet of rate increased per epoch */ function setEpochConfig(uint32 blocks, uint32 roi) public onlyOwner { require(blocks > 0, "AGL::setEpochConfig: zero blocks"); require(roi < 10000, "AGL::setEpochConfig: roi exceeds max fraction"); EpochConfig memory prevEC = epochConfigs[epochConfigs.length - 1]; EpochConfig memory newEC = EpochConfig(getEpochs(block.number), blocks, roi); require(prevEC.blocks != newEC.blocks || prevEC.roi != newEC.roi, "AGL::setEpochConfig: blocks and roi same as before"); //if (prevEC.epoch == newEC.epoch && epochConfigs.length > 1) { if (prevEC.epoch == newEC.epoch) { epochConfigs[epochConfigs.length - 1] = newEC; } else { epochConfigs.push(newEC); } emit EpochConfigChanged(prevEC.epoch, prevEC.blocks, prevEC.roi, newEC.epoch, newEC.blocks, newEC.roi); } /** * @notice Gets block counter per epoch * @return The count of blocks for current epoch */ function getCurrentEpochBlocks() public view returns (uint32 blocks) { blocks = epochConfigs[epochConfigs.length - 1].blocks; } /** * @notice Gets rate of interest for current epoch * @return The rate of interest for current epoch */ function getCurrentEpochROI() public view returns (uint32 roi) { roi = epochConfigs[epochConfigs.length - 1].roi; } /** * @notice Gets current epoch config * @return The EpochConfig for current epoch */ function getCurrentEpochConfig() public view returns (uint32 epoch, uint32 blocks, uint32 roi) { EpochConfig memory ec = epochConfigs[epochConfigs.length - 1]; epoch = ec.epoch; blocks = ec.blocks; roi = ec.roi; } /** * @notice Gets epoch config at given epoch index * @param forEpoch epoch * @return (index of config, config at epoch) */ function getEpochConfig(uint32 forEpoch) public view returns (uint32 index, uint32 epoch, uint32 blocks, uint32 roi) { index = uint32(epochConfigs.length - 1); // solhint-disable-next-line no-inline-assembly for (; index > 0; index--) { if (forEpoch >= epochConfigs[index].epoch) { break; } } EpochConfig memory ec = epochConfigs[index]; epoch = ec.epoch; blocks = ec.blocks; roi = ec.roi; } /** * @notice Gets epoch index at given block number * @param blockNumber The number of blocks * @return epoch index */ function getEpochs(uint blockNumber) public view returns (uint32) { uint96 blocks = 0; uint96 epoch = 0; uint blockNum = blockNumber; for (uint32 i = 0; i < epochConfigs.length; i++) { uint96 deltaBlocks = (uint96(epochConfigs[i].epoch) - epoch) * blocks; if (blockNum < deltaBlocks) { break; } blockNum = blockNum - deltaBlocks; epoch = epochConfigs[i].epoch; blocks = epochConfigs[i].blocks; } if (blocks == 0) { blocks = getCurrentEpochBlocks(); } epoch = epoch + uint96(blockNum / blocks); if (epoch >= 2**32) { epoch = 2**32 - 1; } return uint32(epoch); } /** * @notice Gets the current holding rewart amount for `account` * @param account The address to get holding reward amount * @return The number of current holding reward for `account` */ function getHoldingReward(address account) public view returns (uint96) { // Check if account is holding more than eligible delay uint32 nTransferPoint = numTransferPoints[account]; if (nTransferPoint == 0) { return 0; } uint32 lastEpoch = getEpochs(block.number); if (lastEpoch == 0) { return 0; } lastEpoch = lastEpoch - 1; if (lastEpoch < eligibleEpochs) { return 0; } else { uint32 lastEligibleEpoch = lastEpoch - eligibleEpochs; // Next check implicit zero balance if (transferPoints[account][0].epoch > lastEligibleEpoch) { return 0; } // First check most recent balance if (transferPoints[account][nTransferPoint - 1].epoch <= lastEligibleEpoch) { nTransferPoint = nTransferPoint - 1; } else { uint32 upper = nTransferPoint - 1; nTransferPoint = 0; while (upper > nTransferPoint) { uint32 center = upper - (upper - nTransferPoint) / 2; // ceil, avoiding overflow TransferPoint memory tp = transferPoints[account][center]; if (tp.epoch == lastEligibleEpoch) { nTransferPoint = center; break; } if (tp.epoch < lastEligibleEpoch) { nTransferPoint = center; } else { upper = center - 1; } } } } // Calculate total rewards amount uint256 reward = 0; for (uint32 iTP = 0; iTP <= nTransferPoint; iTP++) { TransferPoint memory tp = transferPoints[account][iTP]; (uint32 iEC,,,uint32 roi) = getEpochConfig(tp.epoch); uint32 startEpoch = tp.epoch; for (; iEC < epochConfigs.length; iEC++) { uint32 epoch = lastEpoch; bool tookNextTP = false; if (iEC < (epochConfigs.length - 1) && epoch > epochConfigs[iEC + 1].epoch) { epoch = epochConfigs[iEC + 1].epoch; } if (iTP < nTransferPoint && epoch > transferPoints[account][iTP + 1].epoch) { epoch = transferPoints[account][iTP + 1].epoch; tookNextTP = true; } reward = reward + (uint256(tp.balance) * roi * sub32(epoch, startEpoch, "AGL::getHoldingReward: invalid epochs")); if (tookNextTP) { break; } startEpoch = epoch; if (iEC < (epochConfigs.length - 1)) { roi = epochConfigs[iEC + 1].roi; } } } uint96 amount = safe96(reward / 10000, "AGL::getHoldingReward: reward exceeds 96 bits"); // Exclude already claimed amount if (claimedAmounts[account] > 0) { amount = sub96(amount, claimedAmounts[account], "AGL::getHoldingReward: invalid claimed amount"); } return amount; } /** * @notice Receive the current holding rewart amount to msg.sender */ function claimReward() public { uint96 holdingReward = getHoldingReward(msg.sender); if (balances[address(this)] < holdingReward) { holdingReward = balances[address(this)]; } claimedAmounts[msg.sender] = add96(claimedAmounts[msg.sender], holdingReward, "AGL::claimReward: invalid claimed amount"); _transferTokens(address(this), msg.sender, holdingReward); } 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), "AGL::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "AGL::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "AGL::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "AGL::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); if (amount > 0) { _writeTransferPoint(src, dst, numTransferPoints[dst], balances[src], balances[dst]); } } 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, "AGL::_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, "AGL::_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, "AGL::_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 _writeTransferPoint(address src, address dst, uint32 nDstPoint, uint96 srcBalance, uint96 dstBalance) internal { uint32 epoch = getEpochs(block.number); if (src != address(this)) { // Revoke sender in reward eligible list for (uint32 i = 0; i < numTransferPoints[src]; i++) { delete transferPoints[src][i]; } // Remove claim amount claimedAmounts[src] = 0; // delete transferPoints[src]; if (srcBalance > 0) { transferPoints[src][0] = TransferPoint(epoch, srcBalance); numTransferPoints[src] = 1; } else { numTransferPoints[src] = 0; } } if (dst != address(this)) { // Add recipient in reward eligible list if (nDstPoint > 0 && transferPoints[dst][nDstPoint - 1].epoch >= epoch) { transferPoints[dst][nDstPoint - 1].balance = dstBalance; } else { transferPoints[dst][nDstPoint] = TransferPoint(epoch, dstBalance); numTransferPoints[dst] = nDstPoint + 1; } } // emit TransferPointChanged(src, balances[src], dst, balances[dst]); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, errorMessage); return c; } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); return a - b; } 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; assembly { chainId := chainid() } return chainId; } }
@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./ Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { return msg.data; } }
1,022,930
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 8953, 2713, 3885, 16, 358, 5309, 16951, 628, 27228, 7940, 715, 7286, 310, 392, 791, 434, 333, 6835, 16, 1492, 1410, 506, 1399, 3970, 16334, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1772, 288, 203, 203, 203, 225, 3885, 1832, 2713, 288, 289, 203, 225, 445, 389, 3576, 12021, 1435, 2713, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 565, 327, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 225, 445, 389, 3576, 751, 1435, 2713, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 565, 327, 1234, 18, 892, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/interface/ICoFiXERC20.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface ICoFiXERC20 { 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; } // File: contracts/interface/ICoFiXV2Pair.sol pragma solidity 0.6.12; interface ICoFiXV2Pair is ICoFiXERC20 { struct OraclePrice { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 theta; } // All pairs: {ETH <-> ERC20 Token} event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, address outToken, uint outAmount, address indexed to); event Swap( address indexed sender, uint amountIn, uint amountOut, address outToken, 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); function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange); function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange); function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo); // function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function skim(address to) external; function sync() external; function initialize(address, address, string memory, string memory, uint256, uint256) external; /// @dev get Net Asset Value Per Share /// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token} /// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token} /// @return navps The Net Asset Value Per Share (liquidity) represents function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps); /// @dev get initial asset ratio /// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token} /// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token} function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount); } // File: contracts/interface/ICoFiXStakingRewards.sol pragma solidity 0.6.12; interface ICoFiXStakingRewards { // Views /// @dev The rewards vault contract address set in factory contract /// @return Returns the vault address function rewardsVault() external view returns (address); /// @dev The lastBlock reward applicable /// @return Returns the latest block.number on-chain function lastBlockRewardApplicable() external view returns (uint256); /// @dev Reward amount represents by per staking token function rewardPerToken() external view returns (uint256); /// @dev How many reward tokens a user has earned but not claimed at present /// @param account The target account /// @return The amount of reward tokens a user earned function earned(address account) external view returns (uint256); /// @dev How many reward tokens accrued recently /// @return The amount of reward tokens accrued recently function accrued() external view returns (uint256); /// @dev Get the latest reward rate of this mining pool (tokens amount per block) /// @return The latest reward rate function rewardRate() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited into to this reward pool (mining pool) /// @return The total amount of XTokens deposited in this mining pool function totalSupply() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited by the target account /// @param account The target account /// @return The total amount of XToken deposited in this mining pool function balanceOf(address account) external view returns (uint256); /// @dev Get the address of token for staking in this mining pool /// @return The staking token address function stakingToken() external view returns (address); /// @dev Get the address of token for rewards in this mining pool /// @return The rewards token address function rewardsToken() external view returns (address); // Mutative /// @dev Stake/Deposit into the reward pool (mining pool) /// @param amount The target amount function stake(uint256 amount) external; /// @dev Stake/Deposit into the reward pool (mining pool) for other account /// @param other The target account /// @param amount The target amount function stakeForOther(address other, uint256 amount) external; /// @dev Withdraw from the reward pool (mining pool), get the original tokens back /// @param amount The target amount function withdraw(uint256 amount) external; /// @dev Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external; /// @dev Claim the reward the user earned function getReward() external; function getRewardAndStake() external; /// @dev User exit the reward pool, it's actually withdraw and getReward function exit() external; /// @dev Add reward to the mining pool function addReward(uint256 amount) external; // Events event RewardAdded(address sender, uint256 reward); event Staked(address indexed user, uint256 amount); event StakedForOther(address indexed user, address indexed other, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } // File: contracts/interface/ICoFiXVaultForLP.sol pragma solidity 0.6.12; interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NewPoolAdded(address pool, uint256 index); event PoolEnabled(address pool); event PoolDisabled(address pool); function setGovernance(address _new) external; function setInitCoFiRate(uint256 _new) external; function setDecayPeriod(uint256 _new) external; function setDecayRate(uint256 _new) external; function addPool(address pool) external; function enablePool(address pool) external; function disablePool(address pool) external; function setPoolWeight(address pool, uint256 weight) external; function batchSetPoolWeight(address[] memory pools, uint256[] memory weights) external; function distributeReward(address to, uint256 amount) external; function getPendingRewardOfLP(address pair) external view returns (uint256); function currentPeriod() external view returns (uint256); function currentCoFiRate() external view returns (uint256); function currentPoolRate(address pool) external view returns (uint256 poolRate); function currentPoolRateByPair(address pair) external view returns (uint256 poolRate); /// @dev Get the award staking pool address of pair (XToken) /// @param pair The address of XToken(pair) contract /// @return pool The pool address function stakingPoolForPair(address pair) external view returns (address pool); function getPoolInfo(address pool) external view returns (POOL_STATE state, uint256 weight); function getPoolInfoByPair(address pair) external view returns (POOL_STATE state, uint256 weight); function getEnabledPoolCnt() external view returns (uint256); function getCoFiStakingPool() external view returns (address pool); } // File: contracts/interface/ICoFiXV2Factory.sol pragma solidity 0.6.12; interface ICoFiXV2Factory { // All pairs: {ETH <-> ERC20 Token} event PairCreated(address indexed token, address pair, uint256); event NewGovernance(address _new); event NewController(address _new); event NewFeeReceiver(address _new); event NewFeeVaultForLP(address token, address feeVault); event NewVaultForLP(address _new); event NewVaultForTrader(address _new); event NewVaultForCNode(address _new); event NewDAO(address _new); /// @dev Create a new token pair for trading /// @param token the address of token to trade /// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @return pair the address of new token pair function createPair( address token, uint256 initToken0Amount, uint256 initToken1Amount ) external returns (address pair); function getPair(address token) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function getTradeMiningStatus(address token) external view returns (bool status); function setTradeMiningStatus(address token, bool status) external; function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs function setFeeVaultForLP(address token, address feeVault) external; function setGovernance(address _new) external; function setController(address _new) external; function setFeeReceiver(address _new) external; function setVaultForLP(address _new) external; function setVaultForTrader(address _new) external; function setVaultForCNode(address _new) external; function setDAO(address _new) external; function getController() external view returns (address controller); function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders function getVaultForLP() external view returns (address vaultForLP); function getVaultForTrader() external view returns (address vaultForTrader); function getVaultForCNode() external view returns (address vaultForCNode); function getDAO() external view returns (address dao); } // File: @openzeppelin/contracts/utils/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 () 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; } } // File: contracts/interface/ICoFiXV2VaultForTrader.sol pragma solidity 0.6.12; interface ICoFiXV2VaultForTrader { event RouterAllowed(address router); event RouterDisallowed(address router); event ClearPendingRewardOfCNode(uint256 pendingAmount); event ClearPendingRewardOfLP(uint256 pendingAmount); function setGovernance(address gov) external; // function setExpectedYieldRatio(uint256 r) external; // function setLRatio(uint256 lRatio) external; // function setTheta(uint256 theta) external; function setCofiRate(uint256 cofiRate) external; function allowRouter(address router) external; function disallowRouter(address router) external; function calcMiningRate(address pair, uint256 neededETHAmount) external view returns (uint256); function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256); function actualMiningAmount(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount); function distributeReward(address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo) external; function clearPendingRewardOfCNode() external; function clearPendingRewardOfLP(address pair) external; function getPendingRewardOfCNode() external view returns (uint256); function getPendingRewardOfLP(address pair) external view returns (uint256); } // File: @openzeppelin/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/interface/ICoFiToken.sol pragma solidity 0.6.12; interface ICoFiToken is IERC20 { /// @dev An event thats emitted when a new governance account is set /// @param _new The new governance address event NewGovernance(address _new); /// @dev An event thats emitted when a new minter account is added /// @param _minter The new minter address added event MinterAdded(address _minter); /// @dev An event thats emitted when a minter account is removed /// @param _minter The minter address removed event MinterRemoved(address _minter); /// @dev Set governance address of CoFi token. Only governance has the right to execute. /// @param _new The new governance address function setGovernance(address _new) external; /// @dev Add a new minter account to CoFi token, who can mint tokens. Only governance has the right to execute. /// @param _minter The new minter address function addMinter(address _minter) external; /// @dev Remove a minter account from CoFi token, who can mint tokens. Only governance has the right to execute. /// @param _minter The minter address removed function removeMinter(address _minter) external; /// @dev mint is used to distribute CoFi token to users, minters are CoFi mining pools /// @param _to The receiver address /// @param _amount The amount of tokens minted function mint(address _to, uint256 _amount) external; } // File: contracts/lib/ABDKMath64x64.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.6.12; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * @dev Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** * @dev Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * 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) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } // File: @openzeppelin/contracts/math/SafeMath.sol 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: contracts/CoFiXV2VaultForTrader.sol pragma solidity 0.6.12; // Reward Pool Controller for Trader // Trade to earn CoFi Token contract CoFiXV2VaultForTrader is ICoFiXV2VaultForTrader, ReentrancyGuard { using SafeMath for uint256; uint256 public constant RATE_BASE = 1e18; uint256 public constant LAMBDA_BASE = 100; // uint256 public constant RECENT_RANGE = 300; uint256 public constant SHARE_BASE = 100; uint256 public constant SHARE_FOR_TRADER = 90; // uint256 public constant SHARE_FOR_LP = 10; uint256 public constant SHARE_FOR_CNODE = 10; // uint256 public constant NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy // make all of these constant, so we can reduce gas cost for swap features // uint256 public constant COFI_DECAY_PERIOD = 2400000; // LP pool yield decays for every 2,400,000 blocks // uint256 public constant THETA_FEE_UINIT = 1 ether; // uint256 public constant L_LIMIT = 100 ether; // uint256 public constant COFI_RATE_UPDATE_INTERVAL = 1000; // uint256 public constant EXPECT_YIELD_BASE = 10; // uint256 public constant L_BASE = 1000; // uint256 public constant THETA_BASE = 1000; // uint256 public constant REWARD_MULTIPLE_BASE = 100; address public immutable cofiToken; address public immutable factory; // managed by governance address public governance; // uint256 public EXPECT_YIELD_RATIO = 3; // r, 0.3 // uint256 public L_RATIO = 2; // l, 0.002 // uint256 public THETA = 2; // 0.002 uint256 public cofiRate = 0.1*1e18; // nt 0.1 uint256 public pendingRewardsForCNode; mapping(address => uint256) public pendingRewardsForLP; // pair address to pending rewards amount mapping (address => bool) public routerAllowed; mapping (address => uint128) public lastMinedBlock; // last block mined cofi token mapping (address => uint256) public lastNeededETHAmount; // last needed eth amount for adjustment mapping (address => uint256) public lastTotalAccruedAmount; uint128 public lastDensity; // last mining density, see currentDensity() modifier onlyGovernance() { require(msg.sender == governance, "CVaultForTrader: !governance"); _; } constructor(address cofi, address _factory) public { cofiToken = cofi; factory = _factory; governance = msg.sender; } /* setters for protocol governance */ function setGovernance(address _new) external override onlyGovernance { governance = _new; } // function setExpectedYieldRatio(uint256 r) external override onlyGovernance { // EXPECT_YIELD_RATIO = r; // } // function setLRatio(uint256 lRatio) external override onlyGovernance { // L_RATIO = lRatio; // } // function setTheta(uint256 theta) external override onlyGovernance { // THETA = theta; // } function setCofiRate(uint256 _cofiRate) external override onlyGovernance { cofiRate = _cofiRate; } function allowRouter(address router) external override onlyGovernance { require(!routerAllowed[router], "CVaultForTrader: router allowed"); routerAllowed[router] = true; emit RouterAllowed(router); } function disallowRouter(address router) external override onlyGovernance { require(routerAllowed[router], "CVaultForTrader: router disallowed"); routerAllowed[router] = false; emit RouterDisallowed(router); } // calc v_t function calcMiningRate(address pair, uint256 neededETHAmount) public override view returns (uint256) { uint256 _lastNeededETHAmount = lastNeededETHAmount[pair]; if (_lastNeededETHAmount > neededETHAmount) { // D_{t-1} > D_t // \frac{D_{t-1} - D_t}{D_{t-1}} return _lastNeededETHAmount.sub(neededETHAmount).mul(RATE_BASE).div(_lastNeededETHAmount); // v_t } else { // D_{t-1} <= D_t return 0; // v_t } } // calc D_t :needed eth amount for adjusting kt to k0 function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) public override view returns (uint256) { /* D_t = |\frac{E_t * k_0 - U_t}{k_0 + P_t}|\\\\ = \frac{|E_t * \frac{initToken1Amount}{initToken0Amount} - U_t|}{\frac{initToken1Amount}{initToken0Amount} + \frac{erc20Amount}{ethAmount}}\\\\ = \frac{|E_t * initToken1Amount - U_t * initToken0Amount|}{initToken1Amount + \frac{erc20Amount * initToken0Amount}{ethAmount}}\\\\ = \frac{|E_t * initToken1Amount - U_t * initToken0Amount| * ethAmount}{initToken1Amount * ethAmount + erc20Amount * initToken0Amount}\\\\ */ { (uint256 initToken0Amount, uint256 initToken1Amount) = ICoFiXV2Pair(pair).getInitialAssetRatio(); uint256 reserve0MulInitToken1Amount = reserve0.mul(initToken1Amount); uint256 reserve1MulInitToken0Amount = reserve1.mul(initToken0Amount); uint256 diff = calcDiff(reserve0MulInitToken1Amount, reserve1MulInitToken0Amount); uint256 diffMulEthAmount = diff.mul(ethAmount); uint256 initToken1AmountMulEthAmount = initToken1Amount.mul(ethAmount); uint256 erc20AmountMulInitToken0Amount = erc20Amount.mul(initToken0Amount); return diffMulEthAmount.div(initToken1AmountMulEthAmount.add(erc20AmountMulInitToken0Amount)); } } function calcDiff(uint x, uint y) private pure returns (uint) { return x > y ? (x - y) : (y - x); } /* Y_t = Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1) - Z_t Z_t = [Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1)] * v_t */ function actualMiningAmount( address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount ) public override view returns ( uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount ) { uint256 totalAmount; { // Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1) uint256 _lastTotalAccruedAmount = lastTotalAccruedAmount[pair]; // Y_{t - 1} uint256 _lastNeededETHAmount = lastNeededETHAmount[pair]; // D_{t - 1} uint256 _lastBlock = lastMinedBlock[pair]; uint256 _offset = block.number.sub(_lastBlock); // s_t totalAmount = _lastTotalAccruedAmount.add(_lastNeededETHAmount.mul(cofiRate).mul(_offset.add(1)).div(RATE_BASE)); } neededETHAmount = calcNeededETHAmountForAdjustment(pair, reserve0, reserve1, ethAmount, erc20Amount); // D_t uint256 miningRate = calcMiningRate(pair, neededETHAmount); // v_t // Z_t = [Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1)] * v_t amount = totalAmount.mul(miningRate).div(RATE_BASE); // Y_t = Y_{t - 1} + D_{t - 1} * n_t * (S_t + 1) - Z_t totalAccruedAmount = totalAmount.sub(amount); } function distributeReward( address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo ) external override nonReentrant { require(routerAllowed[msg.sender], "CVaultForTrader: not allowed router"); // caution: be careful when adding new router require(pair != address(0), "CVaultForTrader: invalid pair"); require(rewardTo != address(0), "CVaultForTrader: invalid rewardTo"); uint256 amount; { uint256 totalAccruedAmount; uint256 neededETHAmount; (uint256 reserve0, uint256 reserve1) = ICoFiXV2Pair(pair).getReserves(); (amount, totalAccruedAmount, neededETHAmount) = actualMiningAmount(pair, reserve0, reserve1, ethAmount, erc20Amount); lastMinedBlock[pair] = uint128(block.number); // uint128 is enough for block.number lastTotalAccruedAmount[pair] = totalAccruedAmount; lastNeededETHAmount[pair] = neededETHAmount; } { uint256 amountForTrader = amount.mul(SHARE_FOR_TRADER).div(SHARE_BASE); // uint256 amountForLP = amount.mul(SHARE_FOR_LP).div(SHARE_BASE); uint256 amountForCNode = amount.mul(SHARE_FOR_CNODE).div(SHARE_BASE); ICoFiToken(cofiToken).mint(rewardTo, amountForTrader); // allows zero, send to receiver directly, reduce gas cost // pendingRewardsForLP[pair] = pendingRewardsForLP[pair].add(amountForLP); // possible key: token or pair, we use pair here pendingRewardsForCNode = pendingRewardsForCNode.add(amountForCNode); } } function clearPendingRewardOfCNode() external override nonReentrant { address vaultForCNode = ICoFiXV2Factory(factory).getVaultForCNode(); require(msg.sender == vaultForCNode, "CVaultForTrader: only vaultForCNode"); // caution // uint256 pending = pendingRewardsForCNode; emit ClearPendingRewardOfCNode(pendingRewardsForCNode); pendingRewardsForCNode = 0; // take all, set to 0 // ICoFiToken(cofiToken).mint(msg.sender, pending); // no need to mint from here, we can mint directly in valult } // vaultForLP should ensure passing the correct pair address function clearPendingRewardOfLP(address pair) external override nonReentrant { address vaultForLP = ICoFiXV2Factory(factory).getVaultForLP(); require(msg.sender == vaultForLP, "CVaultForTrader: only vaultForLP"); // caution emit ClearPendingRewardOfLP(pendingRewardsForLP[pair]); pendingRewardsForLP[pair] = 0; // take all, set to 0 // ICoFiToken(cofiToken).mint(to, pending); // no need to mint from here, we can mint directly in valult } function getPendingRewardOfCNode() external override view returns (uint256) { return pendingRewardsForCNode; } function getPendingRewardOfLP(address pair) external override view returns (uint256) { return pendingRewardsForLP[pair]; } }
last mining density, see currentDensity()
uint128 public lastDensity;
356,234
[ 1, 2722, 1131, 310, 12142, 16, 2621, 783, 23309, 1435, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 10392, 1071, 1142, 23309, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x40238A380092c3A3866A0F98d53304a40E16bD82/sources/contracts/ERC721IA.sol
@dev Removes the Offer if the owner no Longer Owns the NFTs
function _removeInvalidOffer(uint256 _tokenId, address _offeror )internal virtual { TradeOffer memory targetTradeOffer = tradeoffers[_tokenId][_offeror]; delete tradeoffers[_tokenId][_offeror]; emit TradeOfferRemoved(_tokenId, targetTradeOffer.offeror); }
1,925,794
[ 1, 6220, 326, 25753, 309, 326, 3410, 1158, 511, 265, 693, 14223, 2387, 326, 423, 4464, 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 ]
[ 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, 389, 4479, 1941, 10513, 12, 11890, 5034, 389, 2316, 548, 16, 1758, 389, 23322, 280, 262, 7236, 5024, 288, 203, 3639, 2197, 323, 10513, 3778, 1018, 22583, 10513, 273, 18542, 3674, 414, 63, 67, 2316, 548, 6362, 67, 23322, 280, 15533, 203, 3639, 1430, 18542, 3674, 414, 63, 67, 2316, 548, 6362, 67, 23322, 280, 15533, 203, 3639, 3626, 2197, 323, 10513, 10026, 24899, 2316, 548, 16, 1018, 22583, 10513, 18, 23322, 280, 1769, 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 ]
./partial_match/1/0xB7c9E99Da8A857cE576A830A9c19312114d9dE02/sources/Team.sol
how a user identifies their stakes. Each period stake increments stakeID.
uint stakeID;
3,725,984
[ 1, 13606, 279, 729, 25283, 3675, 384, 3223, 18, 8315, 3879, 384, 911, 17071, 384, 911, 734, 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, 384, 911, 734, 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 ]
./full_match/1/0x8a1e51DFe708545D6ad080a0eBBDd18A1b6F860C/sources/contracts/Authorizable.sol
* @notice admin address is Admin address/* @notice verifier address is Verifier address/* @notice Emit event when set an address to a admin/* @notice Emit event when set an address to a verififer/
modifier onlyAdmin() { require(_msgSender() == admin, "Ownable: Caller is not admin"); _; }
2,979,597
[ 1, 3666, 1758, 353, 7807, 1758, 19, 225, 20130, 1758, 353, 6160, 1251, 1758, 19, 225, 16008, 871, 1347, 444, 392, 1758, 358, 279, 3981, 19, 225, 16008, 871, 1347, 444, 392, 1758, 358, 279, 1924, 430, 21549, 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, 202, 20597, 1338, 4446, 1435, 288, 203, 202, 202, 6528, 24899, 3576, 12021, 1435, 422, 3981, 16, 315, 5460, 429, 30, 20646, 353, 486, 3981, 8863, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IDistributeV1 interface IDistributeV1 { function claim(address _to, uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external; } // Part: IKToken interface IKToken { function underlying() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function mint(address recipient, uint256 amount) external returns (bool); function burnFrom(address sender, uint256 amount) external; function addMinter(address sender) external; function renounceMinter() external; } // Part: IName interface IName { function name() external view returns (string memory); } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: ILiquidityPool interface ILiquidityPool { function depositFeeInBips() external view returns (uint256); function kToken(address _token) external view returns (IKToken); function register(IKToken _kToken) external; function renounceOperator() external; function deposit(address _token, uint256 _amount) external payable returns (uint256); function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external; function borrowableBalance(address _token) external view returns (uint256); function underlyingBalance(address _token, address _owner) external view returns (uint256); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function apiVersion() external pure returns (string memory); function withdraw(uint256 shares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: iearn-finance/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay = 0; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay = 86400; // ~ once a day // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor = 100; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold = 0; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: iearn-finance/[email protected]/BaseStrategyInitializable abstract contract BaseStrategyInitializable is BaseStrategy { constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external { _initialize(_vault, _strategist, _rewards, _keeper); } } // File: Strategy.sol contract Strategy is BaseStrategyInitializable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Cloned(address indexed clone); IUniswapV2Router02 constant public uniswapRouter = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); IUniswapV2Router02 constant public sushiswapRouter = IUniswapV2Router02(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)); IERC20 public constant weth = IERC20(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)); IERC20 public constant rook = IERC20(address(0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a)); IUniswapV2Router02 public router; IDistributeV1 public distributor; IKToken public kToken; ILiquidityPool public pool; address public treasury; address[] public path; address[] public wethWantPath; // unsigned. Indicates the losses incurred from the protocol's deposit fees uint256 public incurredLosses; // amount to send to treasury. Used for future governance voting power uint256 public percentKeep; uint256 public constant _denominator = 10000; constructor(address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) public BaseStrategyInitializable(_vault) { _init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); } function clone( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) external returns (address payable newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); emit Cloned(newStrategy); } function init( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) external { super._initialize(_vault, _strategist, _rewards, _keeper); _init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); } function _init( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) internal { // You can set these parameters on deployment to whatever you want // maxReportDelay = 6300; // profitFactor = 100; // debtThreshold = 0; // check to see if KeeperDao can actually accept want (renBTC, DAI, USDC, ETH, WETH) pool = ILiquidityPool(address(_pool)); kToken = pool.kToken(address(want)); require(address(kToken) != address(0x0), "Protocol doesn't support this token!"); want.safeApprove(address(pool), uint256(- 1)); kToken.approve(address(pool), uint256(- 1)); treasury = address(_voter); rook.approve(address(uniswapRouter), uint256(- 1)); rook.approve(address(sushiswapRouter), uint256(- 1)); distributor = IDistributeV1(address(_rewardDistributor)); if (address(want) == address(weth)) { path = [address(rook), address(weth)]; } else { path = [address(rook), address(weth), address(want)]; wethWantPath = [address(weth), address(want)]; } } function name() external view override returns (string memory) { // Add your own name here, suggestion e.g. "StrategyCreamYFI" return string( abi.encodePacked("StrategyRook ", IName(address(want)).name()) ); } function estimatedTotalAssets() public view override returns (uint256) { return valueOfStaked().add(balanceOfUnstaked()).add(valueOfReward()); } function balanceOfUnstaked() public view returns (uint256){ return want.balanceOf(address(this)); } // valued in wants function valueOfStaked() public view returns (uint256){ return pool.underlyingBalance(address(want), address(this)); } // kTokens have different virtual prices. Balance != want function balanceOfStaked() public view returns (uint256){ return kToken.balanceOf(address(this)); } function balanceOfReward() public view returns (uint256){ return rook.balanceOf(address(this)); } function valueOfReward() public view returns (uint256){ return _estimateAmountsOut(rook.balanceOf(address(this)), path); } // only way to find out is thru calculating a virtual price this way // TODO: return a reasonable value when div(0) function _inKTokens(uint256 wantAmount) internal view returns (uint256){ return wantAmount.mul(balanceOfStaked()).div(valueOfStaked()); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ // NOTE: Return `_profit` which is value generated by all positions, priced in `want` // NOTE: Should try to free up at least `_debtOutstanding` of underlying position // sell any reward, leave some for treasury uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } // from selling rewards uint256 profit = balanceOfUnstaked(); // this should be guaranteed if called by keeper. See {harvestTrigger()} if (profit > incurredLosses) { // we want strategy to pay off its own incurredLosses from deposit fees first so it doesn't have to report _loss to the vault _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } } else { _loss = incurredLosses.sub(profit); } // loss has been recorded. incurredLosses = 0; if (_debtOutstanding > _profit) { // withdraw just enough to pay off debt uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); } else { _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } function adjustPosition(uint256 _debtOutstanding) internal override { // NOTE: Try to adjust positions so that `_debtOutstanding` can be freed up on *next* harvest (not immediately) // deposit any loose balance uint256 unstaked = balanceOfUnstaked(); if (unstaked > 0) { _provideLiquidity(unstaked); } } // NAV premium of 0.64% when depositing everytime. Need to keep track of this for _loss calculation. function _provideLiquidity(uint256 _amount) private { uint256 stakedBefore = valueOfStaked(); pool.deposit(address(want), _amount); uint256 stakedAfter = valueOfStaked(); uint256 stakedDelta = stakedAfter.sub(stakedBefore); uint256 depositFee = _amount.sub(stakedDelta); uint256 oneAsBips = 10000; uint256 need = depositFee.mul(oneAsBips).div(oneAsBips - pool.depositFeeInBips()); incurredLosses = incurredLosses.add(need); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // if _amountNeeded is more than currently available, need to unstake some and/or sell rewards to free up assets uint256 unstaked = balanceOfUnstaked(); if (_amountNeeded > unstaked) { uint256 desiredWithdrawAmount = _amountNeeded.sub(unstaked); // can't withdraw more than staked uint256 actualWithdrawAmount = Math.min(desiredWithdrawAmount, valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(actualWithdrawAmount)); _liquidatedAmount = balanceOfUnstaked(); // already withdrew all that it could, any difference left is considered _loss, // which is possible because of KeeperDao's initial deposit NAV premium of 0.64% // i.e initial 10,000 deposit -> 9,936 in pool. If withdraw immediately, _loss = 64 _loss = _amountNeeded.sub(_liquidatedAmount); } else { // already have all of _amountNeeded unstaked _liquidatedAmount = _amountNeeded; _loss = 0; } return (_liquidatedAmount, _loss); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary // Since claiming reward is done asynchronously, rewards could sit idle in strategy before next harvest() call // See {claimRewards()} for detail function prepareMigration(address _newStrategy) internal override { kToken.transfer(_newStrategy, balanceOfStaked()); rook.transfer(_newStrategy, balanceOfReward()); } // Trigger harvest only if strategy has rewards, otherwise, there's nothing to harvest. // This logic is added on top of existing gas efficient harvestTrigger() in the parent class function harvestTrigger(uint256 callCost) public override view returns (bool) { return super.harvestTrigger(_estimateAmountsOut(callCost, wethWantPath)) && balanceOfReward() > 0 && netPositive(); } // Indicator for whether strategy has earned enough rewards to offset incurred losses. // Adding this to harvestTrigger() will ensure that strategy will never have to report a positive _loss to the vault and lower its trust function netPositive() public view returns (bool){ return valueOfReward() > incurredLosses; } // Has to be called manually since this requires off-chain data. // Needs to be called before harvesting otherwise there's nothing to harvest. function claimRewards(uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external onlyKeepers { require(_earningsToDate > 0, "You are trying to claim 0 rewards"); distributor.claim(address(this), _earningsToDate, _nonce, _signature); } function claimRewards(uint256 _earningsToDate, uint256 _nonce, bytes memory _signature, address _distributor) external onlyKeepers { require(_earningsToDate > 0, "You are trying to claim 0 rewards"); IDistributeV1(address(_distributor)).claim(address(this), _earningsToDate, _nonce, _signature); } function _sell(uint256 _amount) internal { // since claiming is async, no point in selling if strategy hasn't claimed rewards uniswapRouter.swapExactTokensForTokens(_amount, uint256(0), path, address(this), now); } function _estimateAmountsOut(uint256 _amount, address[] memory sellPath) public view returns (uint256){ uint256 amountOut = 0; if (sellPath.length <= 0) { return _amount; } if (_amount > 0) { amountOut = uniswapRouter.getAmountsOut(_amount, sellPath)[sellPath.length - 1]; } return amountOut; } function protectedTokens() internal view override returns (address[] memory){ address[] memory protected = new address[](2); protected[0] = address(kToken); protected[1] = address(rook); return protected; } function setKeep(uint256 _percentKeep) external onlyGovernance { percentKeep = _percentKeep; } function setDistributor(address _distributor) external onlyGovernance { distributor = IDistributeV1(address(_distributor)); } function setTreasury(address _treasury) external onlyGovernance { treasury = _treasury; } function setLiquidityPool(address _pool) external onlyGovernance { want.safeApprove(address(_pool), uint256(- 1)); kToken.approve(address(_pool), uint256(- 1)); pool = ILiquidityPool(_pool); } function currentDepositFee() external view returns (uint256){ return pool.depositFeeInBips(); } function switchDex(bool isUniswap) external onlyAuthorized { if (isUniswap) router = uniswapRouter; else router = sushiswapRouter; } receive() external payable {} }
unsigned. Indicates the losses incurred from the protocol's deposit fees amount to send to treasury. Used for future governance voting power
contract Strategy is BaseStrategyInitializable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Cloned(address indexed clone); IUniswapV2Router02 constant public uniswapRouter = IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)); IUniswapV2Router02 constant public sushiswapRouter = IUniswapV2Router02(address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F)); IERC20 public constant weth = IERC20(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)); IERC20 public constant rook = IERC20(address(0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a)); IUniswapV2Router02 public router; IDistributeV1 public distributor; IKToken public kToken; ILiquidityPool public pool; address public treasury; address[] public path; address[] public wethWantPath; uint256 public incurredLosses; uint256 public percentKeep; uint256 public constant _denominator = 10000; constructor(address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) public BaseStrategyInitializable(_vault) { _init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); } function clone( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) external returns (address payable newStrategy) { bytes20 addressBytes = bytes20(address(this)); assembly { let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); emit Cloned(newStrategy); } function clone( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) external returns (address payable newStrategy) { bytes20 addressBytes = bytes20(address(this)); assembly { let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); emit Cloned(newStrategy); } function init( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) external { super._initialize(_vault, _strategist, _rewards, _keeper); _init(_vault, _strategist, _rewards, _keeper, _pool, _voter, _rewardDistributor); } function _init( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) internal { pool = ILiquidityPool(address(_pool)); kToken = pool.kToken(address(want)); require(address(kToken) != address(0x0), "Protocol doesn't support this token!"); want.safeApprove(address(pool), uint256(- 1)); kToken.approve(address(pool), uint256(- 1)); treasury = address(_voter); rook.approve(address(uniswapRouter), uint256(- 1)); rook.approve(address(sushiswapRouter), uint256(- 1)); distributor = IDistributeV1(address(_rewardDistributor)); if (address(want) == address(weth)) { path = [address(rook), address(weth)]; path = [address(rook), address(weth), address(want)]; wethWantPath = [address(weth), address(want)]; } } function _init( address _vault, address _strategist, address _rewards, address _keeper, address _pool, address _voter, address _rewardDistributor ) internal { pool = ILiquidityPool(address(_pool)); kToken = pool.kToken(address(want)); require(address(kToken) != address(0x0), "Protocol doesn't support this token!"); want.safeApprove(address(pool), uint256(- 1)); kToken.approve(address(pool), uint256(- 1)); treasury = address(_voter); rook.approve(address(uniswapRouter), uint256(- 1)); rook.approve(address(sushiswapRouter), uint256(- 1)); distributor = IDistributeV1(address(_rewardDistributor)); if (address(want) == address(weth)) { path = [address(rook), address(weth)]; path = [address(rook), address(weth), address(want)]; wethWantPath = [address(weth), address(want)]; } } } else { function name() external view override returns (string memory) { return string( abi.encodePacked("StrategyRook ", IName(address(want)).name()) ); } function estimatedTotalAssets() public view override returns (uint256) { return valueOfStaked().add(balanceOfUnstaked()).add(valueOfReward()); } function balanceOfUnstaked() public view returns (uint256){ return want.balanceOf(address(this)); } function valueOfStaked() public view returns (uint256){ return pool.underlyingBalance(address(want), address(this)); } function balanceOfStaked() public view returns (uint256){ return kToken.balanceOf(address(this)); } function balanceOfReward() public view returns (uint256){ return rook.balanceOf(address(this)); } function valueOfReward() public view returns (uint256){ return _estimateAmountsOut(rook.balanceOf(address(this)), path); } function _inKTokens(uint256 wantAmount) internal view returns (uint256){ return wantAmount.mul(balanceOfStaked()).div(valueOfStaked()); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } uint256 profit = balanceOfUnstaked(); function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } } else { incurredLosses = 0; function prepareReturn(uint256 _debtOutstanding) internal override returns (uint256 _profit, uint256 _loss, uint256 _debtPayment){ uint256 rewards = balanceOfReward(); if (rewards > 0) { uint256 rewardsForVoting = rewards.mul(percentKeep).div(_denominator); if (rewardsForVoting > 0) { IERC20(rook).safeTransfer(treasury, rewardsForVoting); } uint256 rewardsRemaining = balanceOfReward(); if (rewardsRemaining > 0) { _sell(rewardsRemaining); } } if (profit > incurredLosses) { _profit = profit.sub(incurredLosses); if (incurredLosses > 0) { pool.deposit(address(want), incurredLosses); incurredLosses = 0; } _loss = incurredLosses.sub(profit); } if (_debtOutstanding > _profit) { uint256 _toWithdraw = Math.min(_debtOutstanding.sub(_profit), valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(_toWithdraw)); _debtPayment = Math.min(_debtOutstanding, balanceOfUnstaked()); _debtPayment = _debtOutstanding; _profit = _profit.sub(_debtOutstanding); } return (_profit, _loss, _debtPayment); } } else { function adjustPosition(uint256 _debtOutstanding) internal override { uint256 unstaked = balanceOfUnstaked(); if (unstaked > 0) { _provideLiquidity(unstaked); } } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 unstaked = balanceOfUnstaked(); if (unstaked > 0) { _provideLiquidity(unstaked); } } function _provideLiquidity(uint256 _amount) private { uint256 stakedBefore = valueOfStaked(); pool.deposit(address(want), _amount); uint256 stakedAfter = valueOfStaked(); uint256 stakedDelta = stakedAfter.sub(stakedBefore); uint256 depositFee = _amount.sub(stakedDelta); uint256 oneAsBips = 10000; uint256 need = depositFee.mul(oneAsBips).div(oneAsBips - pool.depositFeeInBips()); incurredLosses = incurredLosses.add(need); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 unstaked = balanceOfUnstaked(); if (_amountNeeded > unstaked) { uint256 desiredWithdrawAmount = _amountNeeded.sub(unstaked); uint256 actualWithdrawAmount = Math.min(desiredWithdrawAmount, valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(actualWithdrawAmount)); _liquidatedAmount = balanceOfUnstaked(); _loss = _amountNeeded.sub(_liquidatedAmount); _liquidatedAmount = _amountNeeded; _loss = 0; } return (_liquidatedAmount, _loss); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 unstaked = balanceOfUnstaked(); if (_amountNeeded > unstaked) { uint256 desiredWithdrawAmount = _amountNeeded.sub(unstaked); uint256 actualWithdrawAmount = Math.min(desiredWithdrawAmount, valueOfStaked()); pool.withdraw(address(this), kToken, _inKTokens(actualWithdrawAmount)); _liquidatedAmount = balanceOfUnstaked(); _loss = _amountNeeded.sub(_liquidatedAmount); _liquidatedAmount = _amountNeeded; _loss = 0; } return (_liquidatedAmount, _loss); } } else { function prepareMigration(address _newStrategy) internal override { kToken.transfer(_newStrategy, balanceOfStaked()); rook.transfer(_newStrategy, balanceOfReward()); } function harvestTrigger(uint256 callCost) public override view returns (bool) { return super.harvestTrigger(_estimateAmountsOut(callCost, wethWantPath)) && balanceOfReward() > 0 && netPositive(); } function netPositive() public view returns (bool){ return valueOfReward() > incurredLosses; } function claimRewards(uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external onlyKeepers { require(_earningsToDate > 0, "You are trying to claim 0 rewards"); distributor.claim(address(this), _earningsToDate, _nonce, _signature); } function claimRewards(uint256 _earningsToDate, uint256 _nonce, bytes memory _signature, address _distributor) external onlyKeepers { require(_earningsToDate > 0, "You are trying to claim 0 rewards"); IDistributeV1(address(_distributor)).claim(address(this), _earningsToDate, _nonce, _signature); } function _sell(uint256 _amount) internal { uniswapRouter.swapExactTokensForTokens(_amount, uint256(0), path, address(this), now); } function _estimateAmountsOut(uint256 _amount, address[] memory sellPath) public view returns (uint256){ uint256 amountOut = 0; if (sellPath.length <= 0) { return _amount; } if (_amount > 0) { amountOut = uniswapRouter.getAmountsOut(_amount, sellPath)[sellPath.length - 1]; } return amountOut; } function _estimateAmountsOut(uint256 _amount, address[] memory sellPath) public view returns (uint256){ uint256 amountOut = 0; if (sellPath.length <= 0) { return _amount; } if (_amount > 0) { amountOut = uniswapRouter.getAmountsOut(_amount, sellPath)[sellPath.length - 1]; } return amountOut; } function _estimateAmountsOut(uint256 _amount, address[] memory sellPath) public view returns (uint256){ uint256 amountOut = 0; if (sellPath.length <= 0) { return _amount; } if (_amount > 0) { amountOut = uniswapRouter.getAmountsOut(_amount, sellPath)[sellPath.length - 1]; } return amountOut; } function protectedTokens() internal view override returns (address[] memory){ address[] memory protected = new address[](2); protected[0] = address(kToken); protected[1] = address(rook); return protected; } function setKeep(uint256 _percentKeep) external onlyGovernance { percentKeep = _percentKeep; } function setDistributor(address _distributor) external onlyGovernance { distributor = IDistributeV1(address(_distributor)); } function setTreasury(address _treasury) external onlyGovernance { treasury = _treasury; } function setLiquidityPool(address _pool) external onlyGovernance { want.safeApprove(address(_pool), uint256(- 1)); kToken.approve(address(_pool), uint256(- 1)); pool = ILiquidityPool(_pool); } function currentDepositFee() external view returns (uint256){ return pool.depositFeeInBips(); } function switchDex(bool isUniswap) external onlyAuthorized { if (isUniswap) router = uniswapRouter; else router = sushiswapRouter; } receive() external payable {} }
1,623,745
[ 1, 22297, 18, 18336, 326, 24528, 316, 1397, 1118, 628, 326, 1771, 1807, 443, 1724, 1656, 281, 3844, 358, 1366, 358, 9787, 345, 22498, 18, 10286, 364, 3563, 314, 1643, 82, 1359, 331, 17128, 7212, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19736, 353, 3360, 4525, 4435, 6934, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 3905, 8184, 12, 2867, 8808, 3236, 1769, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 5381, 1071, 640, 291, 91, 438, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 2867, 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, 10019, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 5381, 1071, 272, 1218, 291, 91, 438, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 2867, 12, 20, 7669, 29, 73, 21, 71, 41, 4033, 74, 23728, 21, 74, 3247, 69, 41, 10261, 4449, 27, 378, 6028, 69, 22, 952, 69, 29, 39, 6418, 28, 38, 29, 42, 10019, 203, 565, 467, 654, 39, 3462, 1071, 5381, 341, 546, 273, 467, 654, 39, 3462, 12, 2867, 12, 20, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 10019, 203, 565, 467, 654, 39, 3462, 1071, 5381, 721, 601, 273, 467, 654, 39, 3462, 12, 2867, 12, 20, 5841, 37, 25, 3028, 27, 71, 29, 2 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // 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,485,983
[ 1, 146, 227, 145, 113, 145, 120, 145, 125, 145, 118, 145, 126, 146, 242, 146, 229, 146, 239, 225, 145, 126, 145, 113, 225, 145, 125, 145, 118, 145, 124, 145, 127, 146, 234, 146, 239, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 436, 407, 67, 502, 2038, 30, 146, 227, 145, 113, 145, 120, 145, 125, 145, 118, 145, 126, 146, 242, 146, 229, 146, 239, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./GhostOwnership.sol"; contract GhostFactory is GhostOwnership { // TODO: setting authority of calling this method // @notice create egg that ghost with level 0. // Must manage ghost ownership. function createEgg(uint256 _gene, address _owner) external { require(_gene != uint256(0)); require(_owner != address(0)); uint256 tokenId = _createEgg(_gene, _owner); ghostIndexToOwner[tokenId] = _owner; ownershipTokenCount[tokenId]++; } // TODO: calculate ratio of angel and devil // @notice returns ratio of angel and devil. function getGauge() public view returns (uint, uint) { return (0, 0); } // @notice increase level of ghost. function levelUp(uint256 _tokenId) external { _levelUp(_tokenId); } }
TODO: setting authority of calling this method @notice create egg that ghost with level 0. Must manage ghost ownership.
contract GhostFactory is GhostOwnership { function createEgg(uint256 _gene, address _owner) external { require(_gene != uint256(0)); require(_owner != address(0)); uint256 tokenId = _createEgg(_gene, _owner); ghostIndexToOwner[tokenId] = _owner; ownershipTokenCount[tokenId]++; } function getGauge() public view returns (uint, uint) { return (0, 0); } function levelUp(uint256 _tokenId) external { _levelUp(_tokenId); } }
12,576,657
[ 1, 6241, 30, 3637, 11675, 434, 4440, 333, 707, 225, 752, 25144, 716, 314, 2564, 598, 1801, 374, 18, 225, 6753, 10680, 314, 2564, 23178, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 611, 2564, 1733, 353, 611, 2564, 5460, 12565, 288, 203, 203, 565, 445, 25184, 14253, 12, 11890, 5034, 389, 11857, 16, 1758, 389, 8443, 13, 3903, 288, 203, 3639, 2583, 24899, 11857, 480, 2254, 5034, 12, 20, 10019, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 10019, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 2640, 41, 14253, 24899, 11857, 16, 389, 8443, 1769, 203, 203, 3639, 314, 2564, 1016, 774, 5541, 63, 2316, 548, 65, 273, 389, 8443, 31, 203, 3639, 23178, 1345, 1380, 63, 2316, 548, 3737, 15, 31, 203, 565, 289, 203, 203, 565, 445, 7162, 8305, 1435, 1071, 1476, 1135, 261, 11890, 16, 2254, 13, 288, 203, 3639, 327, 261, 20, 16, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 1801, 1211, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 288, 203, 3639, 389, 2815, 1211, 24899, 2316, 548, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./Ownable.sol"; contract UserRegistryStorage is Ownable { // Constants uint constant MAX_LEN = 20; uint constant IPFS_LEN = 46; uint constant ARRAY_MAX_SIZE = 5; // Configs address private logicAddress; // Contract status bool private active; bool private contractTerminated; // Data structures struct User { bool exists; mapping(address => bool) permissions; string name; string imageHash; address[ARRAY_MAX_SIZE] pendingApproval; uint numAddresses; mapping(address => uint) index; } // Variables mapping(address => User) private users; // Events event LogDeposit(address indexed sender); event LogicAddressUpdated( address indexed oldLogicAddress, address indexed newLogicAddress ); event ActiveStatusToggled(bool indexed oldStatus, bool indexed newStatus); event ContractTerminatedPermanently(); // Modifiers modifier onlyFromLogicAddress() { require(msg.sender == logicAddress); _; } modifier stopInEmergency() { require(active); _; } modifier contractAlive() { require(!contractTerminated); _; } // Utility functions constructor() Ownable() public { active = true; contractTerminated = false; } function () public payable contractAlive() { // Fallback payable function to accept ether require(msg.data.length == 0); emit LogDeposit(msg.sender); } function toggleContractActive() public contractAlive() onlyOwner() { // To pause a function in the event of a bug active = !active; emit ActiveStatusToggled(!active, active); } function terminateContractPermanently() public contractAlive() onlyOwner() { // To completely terminate the function (similar to selfdestruct) contractTerminated = true; owner.transfer(address(this).balance); renounceOwnership(); emit ContractTerminatedPermanently(); } function updateLogicAddress(address _logicAddress) public contractAlive() stopInEmergency() onlyOwner() { // Update the logic contract address address oldAddress = logicAddress; logicAddress = _logicAddress; emit LogicAddressUpdated(oldAddress, _logicAddress); } // Setter functions function setRequesteeExists(address requestee, bool _exists) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Set user's existence users[requestee].exists = _exists; } function setRequesterPermission( address requestee, address requester, bool permission ) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Set requesters' permission to view your details users[requestee].permissions[requester] = permission; } function setRequesteeName(address requestee, string _name) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Set your identity name users[requestee].name = _name; } function setRequesteeImageHash(address requestee, string _imageHash) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Set your identity image hash users[requestee].imageHash = _imageHash; } function setRequesteePendingApproval( address requestee, address requester, uint index ) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Add requester's request to requestee's pendingApproval array users[requestee].pendingApproval[index] = requester; } function deleteRequesteePendingApproval(address requestee, uint index) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Delete requester's request from requestee's pendingApproval array delete users[requestee].pendingApproval[index]; } function setRequesteeNumAddresses(address requestee, uint _numAddresses) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Set requestee's number of requests for approval users[requestee].numAddresses = _numAddresses; } function setRequesterPendingApprovalIndex( address requestee, address requester, uint _index ) public contractAlive() stopInEmergency() onlyFromLogicAddress() { // Set requester's request index users[requestee].index[requester] = _index; } // Getter functions function getRequesteeExists(address requestee) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (bool) { // Get user's existence return users[requestee].exists; } function getRequesterPermission(address requestee, address requester) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (bool) { // Get requester's permission from requestee return users[requestee].permissions[requester]; } function getRequesteeName(address requestee) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (string) { // Get your identity's name return users[requestee].name; } function getRequesteeImageHash(address requestee) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (string) { // Get your identity's image hash return users[requestee].imageHash; } function getRequesteePendingApproval(address requestee) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (address[ARRAY_MAX_SIZE]) { // Get your array of approval requests return users[requestee].pendingApproval; } function getRequesteeNumAddresses(address requestee) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (uint) { // Get the number of approval requests return users[requestee].numAddresses; } function getRequesterPendingApprovalIndex( address requestee, address requester ) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (uint) { // Get requester's approval request index return users[requestee].index[requester]; } }
Get the number of approval requests
function getRequesteeNumAddresses(address requestee) public view contractAlive() stopInEmergency() onlyFromLogicAddress() returns (uint) { return users[requestee].numAddresses; }
6,367,756
[ 1, 967, 326, 1300, 434, 23556, 3285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4328, 1340, 2578, 7148, 12, 2867, 590, 1340, 13, 203, 3639, 1071, 203, 3639, 1476, 7010, 3639, 6835, 10608, 1435, 203, 3639, 2132, 382, 1514, 24530, 1435, 203, 3639, 1338, 1265, 20556, 1887, 1435, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 3677, 63, 2293, 1340, 8009, 2107, 7148, 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 ]
./partial_match/42/0xA18eD8349bbeB12d371896f4FE8FE6775Ef5D84c/sources/StrategyOperator.sol
* @title Actions @author Opyn Team @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions./ possible actions that can be performed
library Actions { pragma solidity 0.6.10; enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call } struct ActionArgs { ActionType actionType; address owner; address secondAddress; address asset; uint256 vaultId; uint256 amount; uint256 index; bytes data; } struct MintArgs { address owner; uint256 vaultId; address to; address otoken; uint256 index; uint256 amount; } struct BurnArgs { address owner; uint256 vaultId; address from; address otoken; uint256 index; uint256 amount; } struct OpenVaultArgs { address owner; uint256 vaultId; } struct DepositArgs { address owner; uint256 vaultId; address from; address asset; uint256 index; uint256 amount; } struct RedeemArgs { address receiver; address otoken; uint256 amount; } struct WithdrawArgs { address owner; uint256 vaultId; address to; address asset; uint256 index; uint256 amount; } struct SettleVaultArgs { address owner; uint256 vaultId; address to; } struct CallArgs { address callee; bytes data; } function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require(_args.actionType == ActionType.OpenVault, "Actions: can only parse arguments for open vault actions"); require(_args.owner != address(0), "Actions: cannot open vault for an invalid account"); } return OpenVaultArgs({owner: _args.owner, vaultId: _args.vaultId}); function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require(_args.actionType == ActionType.MintShortOption, "Actions: can only parse arguments for mint actions"); require(_args.owner != address(0), "Actions: cannot mint from an invalid account"); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require(_args.actionType == ActionType.MintShortOption, "Actions: can only parse arguments for mint actions"); require(_args.owner != address(0), "Actions: cannot mint from an invalid account"); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require(_args.actionType == ActionType.BurnShortOption, "Actions: can only parse arguments for burn actions"); require(_args.owner != address(0), "Actions: cannot burn from an invalid account"); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require(_args.actionType == ActionType.BurnShortOption, "Actions: can only parse arguments for burn actions"); require(_args.owner != address(0), "Actions: cannot burn from an invalid account"); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "Actions: can only parse arguments for deposit actions" ); require(_args.owner != address(0), "Actions: cannot deposit to an invalid account"); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "Actions: can only parse arguments for deposit actions" ); require(_args.owner != address(0), "Actions: cannot deposit to an invalid account"); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "Actions: can only parse arguments for withdraw actions" ); require(_args.owner != address(0), "Actions: cannot withdraw from an invalid account"); require(_args.secondAddress != address(0), "Actions: cannot withdraw to an invalid account"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "Actions: can only parse arguments for withdraw actions" ); require(_args.owner != address(0), "Actions: cannot withdraw from an invalid account"); require(_args.secondAddress != address(0), "Actions: cannot withdraw to an invalid account"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require(_args.actionType == ActionType.Redeem, "Actions: can only parse arguments for redeem actions"); require(_args.secondAddress != address(0), "Actions: cannot redeem to an invalid account"); } return RedeemArgs({receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount}); function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require( _args.actionType == ActionType.SettleVault, "Actions: can only parse arguments for settle vault actions" ); require(_args.owner != address(0), "Actions: cannot settle vault for an invalid account"); require(_args.secondAddress != address(0), "Actions: cannot withdraw payout to an invalid account"); } return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress}); function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require(_args.actionType == ActionType.Call, "Actions: can only parse arguments for call actions"); require(_args.secondAddress != address(0), "Actions: target address cannot be address(0)"); } return CallArgs({callee: _args.secondAddress, data: _args.data}); }
3,308,524
[ 1, 6100, 225, 6066, 878, 10434, 225, 432, 5313, 716, 8121, 279, 4382, 2615, 1958, 16, 720, 1953, 434, 4382, 8179, 16, 471, 4186, 358, 1109, 4382, 2615, 1368, 2923, 18765, 18, 19, 3323, 4209, 716, 848, 506, 9591, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 18765, 288, 203, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2163, 31, 203, 565, 2792, 4382, 559, 288, 203, 3639, 3502, 12003, 16, 203, 3639, 490, 474, 4897, 1895, 16, 203, 3639, 605, 321, 4897, 1895, 16, 203, 3639, 4019, 538, 305, 3708, 1895, 16, 203, 3639, 3423, 9446, 3708, 1895, 16, 203, 3639, 4019, 538, 305, 13535, 2045, 287, 16, 203, 3639, 3423, 9446, 13535, 2045, 287, 16, 203, 3639, 1000, 5929, 12003, 16, 203, 3639, 868, 24903, 16, 203, 3639, 3049, 203, 565, 289, 203, 203, 565, 1958, 4382, 2615, 288, 203, 3639, 4382, 559, 1301, 559, 31, 203, 3639, 1758, 3410, 31, 203, 3639, 1758, 2205, 1887, 31, 203, 3639, 1758, 3310, 31, 203, 3639, 2254, 5034, 9229, 548, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 770, 31, 203, 3639, 1731, 501, 31, 203, 565, 289, 203, 203, 565, 1958, 490, 474, 2615, 288, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 5034, 9229, 548, 31, 203, 3639, 1758, 358, 31, 203, 3639, 1758, 320, 2316, 31, 203, 3639, 2254, 5034, 770, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 565, 289, 203, 203, 565, 1958, 605, 321, 2615, 288, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 5034, 9229, 548, 31, 203, 3639, 1758, 628, 31, 203, 3639, 1758, 320, 2316, 31, 203, 3639, 2254, 5034, 770, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 565, 289, 203, 203, 565, 1958, 3502, 12003, 2615, 288, 203, 3639, 1758, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "../governance/Managed.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./DisputeManagerStorage.sol"; import "./IDisputeManager.sol"; /* * @title DisputeManager * @dev Provides a way to align the incentives of participants by having slashing as deterrent * for incorrect behaviour. * * There are two types of disputes that can be created: Query disputes and Indexing disputes. * * Query Disputes: * Graph nodes receive queries and return responses with signed receipts called attestations. * An attestation can be disputed if the consumer thinks the query response was invalid. * Indexers use the derived private key for an allocation to sign attestations. * * Indexing Disputes: * Indexers present a Proof of Indexing (POI) when they close allocations to prove * they were indexing a subgraph. The Staking contract emits that proof with the format * keccak256(indexer.address, POI). * Any challenger can dispute the validity of a POI by submitting a dispute to this contract * along with a deposit. * * Arbitration: * Disputes can only be accepted, rejected or drawn by the arbitrator role that can be delegated * to a EOA or DAO. */ contract DisputeManager is DisputeManagerV1Storage, GraphUpgradeable, IDisputeManager { using SafeMath for uint256; // -- EIP-712 -- bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Protocol"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0xa070ffb1cd7409649bf77822cce74495468e06dbfaef09556838bf188679b9c2; bytes32 private constant RECEIPT_TYPE_HASH = keccak256( "Receipt(bytes32 requestCID,bytes32 responseCID,bytes32 subgraphDeploymentID)" ); // -- Constants -- uint256 private constant ATTESTATION_SIZE_BYTES = 161; uint256 private constant RECEIPT_SIZE_BYTES = 96; uint256 private constant SIG_R_LENGTH = 32; uint256 private constant SIG_S_LENGTH = 32; uint256 private constant SIG_R_OFFSET = RECEIPT_SIZE_BYTES; uint256 private constant SIG_S_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH; uint256 private constant SIG_V_OFFSET = RECEIPT_SIZE_BYTES + SIG_R_LENGTH + SIG_S_LENGTH; uint256 private constant UINT8_BYTE_LENGTH = 1; uint256 private constant BYTES32_BYTE_LENGTH = 32; uint256 private constant MAX_PPM = 1000000; // 100% in parts per million // -- Events -- /** * @dev Emitted when a query dispute is created for `subgraphDeploymentID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman and `attestation` submitted. */ event QueryDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, bytes32 subgraphDeploymentID, bytes attestation ); /** * @dev Emitted when an indexing dispute is created for `allocationID` and `indexer` * by `fisherman`. * The event emits the amount of `tokens` deposited by the fisherman. */ event IndexingDisputeCreated( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens, address allocationID ); /** * @dev Emitted when arbitrator accepts a `disputeID` to `indexer` created by `fisherman`. * The event emits the amount `tokens` transferred to the fisherman, the deposit plus reward. */ event DisputeAccepted( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator rejects a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` burned from the fisherman deposit. */ event DisputeRejected( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when arbitrator draw a `disputeID` for `indexer` created by `fisherman`. * The event emits the amount `tokens` used as deposit and returned to the fisherman. */ event DisputeDrawn( bytes32 indexed disputeID, address indexed indexer, address indexed fisherman, uint256 tokens ); /** * @dev Emitted when two disputes are in conflict to link them. * This event will be emitted after each DisputeCreated event is emitted * for each of the individual disputes. */ event DisputeLinked(bytes32 indexed disputeID1, bytes32 indexed disputeID2); /** * @dev Check if the caller is the arbitrator. */ modifier onlyArbitrator { require(msg.sender == arbitrator, "Caller is not the Arbitrator"); _; } /** * @dev Initialize this contract. * @param _arbitrator Arbitrator role * @param _minimumDeposit Minimum deposit required to create a Dispute * @param _fishermanRewardPercentage Percent of slashed funds for fisherman (ppm) * @param _slashingPercentage Percentage of indexer stake slashed (ppm) */ function initialize( address _controller, address _arbitrator, uint256 _minimumDeposit, uint32 _fishermanRewardPercentage, uint32 _slashingPercentage ) external onlyImpl { Managed._initialize(_controller); // Settings _setArbitrator(_arbitrator); _setMinimumDeposit(_minimumDeposit); _setFishermanRewardPercentage(_fishermanRewardPercentage); _setSlashingPercentage(_slashingPercentage); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function setArbitrator(address _arbitrator) external override onlyGovernor { _setArbitrator(_arbitrator); } /** * @dev Internal: Set the arbitrator address. * @notice Update the arbitrator to `_arbitrator` * @param _arbitrator The address of the arbitration contract or party */ function _setArbitrator(address _arbitrator) private { require(_arbitrator != address(0), "Arbitrator must be set"); arbitrator = _arbitrator; emit ParameterUpdated("arbitrator"); } /** * @dev Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function setMinimumDeposit(uint256 _minimumDeposit) external override onlyGovernor { _setMinimumDeposit(_minimumDeposit); } /** * @dev Internal: Set the minimum deposit required to create a dispute. * @notice Update the minimum deposit to `_minimumDeposit` Graph Tokens * @param _minimumDeposit The minimum deposit in Graph Tokens */ function _setMinimumDeposit(uint256 _minimumDeposit) private { require(_minimumDeposit > 0, "Minimum deposit must be set"); minimumDeposit = _minimumDeposit; emit ParameterUpdated("minimumDeposit"); } /** * @dev Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function setFishermanRewardPercentage(uint32 _percentage) external override onlyGovernor { _setFishermanRewardPercentage(_percentage); } /** * @dev Internal: Set the percent reward that the fisherman gets when slashing occurs. * @notice Update the reward percentage to `_percentage` * @param _percentage Reward as a percentage of indexer stake */ function _setFishermanRewardPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Reward percentage must be below or equal to MAX_PPM"); fishermanRewardPercentage = _percentage; emit ParameterUpdated("fishermanRewardPercentage"); } /** * @dev Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function setSlashingPercentage(uint32 _percentage) external override onlyGovernor { _setSlashingPercentage(_percentage); } /** * @dev Internal: Set the percentage used for slashing indexers. * @param _percentage Percentage used for slashing */ function _setSlashingPercentage(uint32 _percentage) private { // Must be within 0% to 100% (inclusive) require(_percentage <= MAX_PPM, "Slashing percentage must be below or equal to MAX_PPM"); slashingPercentage = _percentage; emit ParameterUpdated("slashingPercentage"); } /** * @dev Return whether a dispute exists or not. * @notice Return if dispute with ID `_disputeID` exists * @param _disputeID True if dispute already exists */ function isDisputeCreated(bytes32 _disputeID) public override view returns (bool) { return disputes[_disputeID].fisherman != address(0); } /** * @dev Get the message hash that an indexer used to sign the receipt. * Encodes a receipt using a domain separator, as described on * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification. * @notice Return the message hash used to sign the receipt * @param _receipt Receipt returned by indexer and submitted by fisherman * @return Message hash used to sign the receipt */ function encodeHashReceipt(Receipt memory _receipt) public override view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", // EIP-191 encoding pad, EIP-712 version 1 DOMAIN_SEPARATOR, keccak256( abi.encode( RECEIPT_TYPE_HASH, _receipt.requestCID, _receipt.responseCID, _receipt.subgraphDeploymentID ) // EIP 712-encoded message hash ) ) ); } /** * @dev Returns if two attestations are conflicting. * Everything must match except for the responseID. * @param _attestation1 Attestation * @param _attestation2 Attestation * @return True if the two attestations are conflicting */ function areConflictingAttestations( Attestation memory _attestation1, Attestation memory _attestation2 ) public override pure returns (bool) { return (_attestation1.requestCID == _attestation2.requestCID && _attestation1.subgraphDeploymentID == _attestation2.subgraphDeploymentID && _attestation1.responseCID != _attestation2.responseCID); } /** * @dev Returns the indexer that signed an attestation. * @param _attestation Attestation * @return Indexer address */ function getAttestationIndexer(Attestation memory _attestation) public override view returns (address) { // Get attestation signer, allocationID address allocationID = _recoverAttestationSigner(_attestation); IStaking.Allocation memory alloc = staking().getAllocation(allocationID); require(alloc.indexer != address(0), "Indexer cannot be found for the attestation"); require( alloc.subgraphDeploymentID == _attestation.subgraphDeploymentID, "Allocation and attestation subgraphDeploymentID must match" ); return alloc.indexer; } /** * @dev Get the fisherman reward for a given indexer stake. * @notice Return the fisherman reward based on the `_indexer` stake * @param _indexer Indexer to be slashed * @return Reward calculated as percentage of the indexer slashed funds */ function getTokensToReward(address _indexer) public override view returns (uint256) { uint256 tokens = getTokensToSlash(_indexer); if (tokens == 0) { return 0; } return uint256(fishermanRewardPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Get the amount of tokens to slash for an indexer based on the current stake. * @param _indexer Address of the indexer * @return Amount of tokens to slash */ function getTokensToSlash(address _indexer) public override view returns (uint256) { uint256 tokens = staking().getIndexerStakedTokens(_indexer); // slashable tokens if (tokens == 0) { return 0; } return uint256(slashingPercentage).mul(tokens).div(MAX_PPM); } /** * @dev Create a query dispute for the arbitrator to resolve. * This function is called by a fisherman that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _attestationData Attestation bytes submitted by the fisherman * @param _deposit Amount of tokens staked as deposit */ function createQueryDispute(bytes calldata _attestationData, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createQueryDisputeWithAttestation( msg.sender, _deposit, _parseAttestation(_attestationData), _attestationData ); } /** * @dev Create query disputes for two conflicting attestations. * A conflicting attestation is a proof presented by two different indexers * where for the same request on a subgraph the response is different. * For this type of dispute the submitter is not required to present a deposit * as one of the attestation is considered to be right. * Two linked disputes will be created and if the arbitrator resolve one, the other * one will be automatically resolved. * @param _attestationData1 First attestation data submitted * @param _attestationData2 Second attestation data submitted * @return DisputeID1, DisputeID2 */ function createQueryDisputeConflict( bytes calldata _attestationData1, bytes calldata _attestationData2 ) external override returns (bytes32, bytes32) { address fisherman = msg.sender; // Parse each attestation Attestation memory attestation1 = _parseAttestation(_attestationData1); Attestation memory attestation2 = _parseAttestation(_attestationData2); // Test that attestations are conflicting require( areConflictingAttestations(attestation1, attestation2), "Attestations must be in conflict" ); // Create the disputes // The deposit is zero for conflicting attestations bytes32 dID1 = _createQueryDisputeWithAttestation( fisherman, 0, attestation1, _attestationData1 ); bytes32 dID2 = _createQueryDisputeWithAttestation( fisherman, 0, attestation2, _attestationData2 ); // Store the linked disputes to be resolved disputes[dID1].relatedDisputeID = dID2; disputes[dID2].relatedDisputeID = dID1; // Emit event that links the two created disputes emit DisputeLinked(dID1, dID2); return (dID1, dID2); } /** * @dev Create a query dispute passing the parsed attestation. * To be used in createQueryDispute() and createQueryDisputeConflict() * to avoid calling parseAttestation() multiple times * `_attestationData` is only passed to be emitted * @param _fisherman Creator of dispute * @param _deposit Amount of tokens staked as deposit * @param _attestation Attestation struct parsed from bytes * @param _attestationData Attestation bytes submitted by the fisherman * @return DisputeID */ function _createQueryDisputeWithAttestation( address _fisherman, uint256 _deposit, Attestation memory _attestation, bytes memory _attestationData ) private returns (bytes32) { // Get the indexer that signed the attestation address indexer = getAttestationIndexer(_attestation); // The indexer is disputable require(staking().hasStake(indexer), "Dispute indexer has no stake"); // Create a disputeID bytes32 disputeID = keccak256( abi.encodePacked( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID, indexer, _fisherman ) ); // Only one dispute for a (indexer, subgraphDeploymentID) at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Store dispute disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0 // no related dispute ); emit QueryDisputeCreated( disputeID, indexer, _fisherman, _deposit, _attestation.subgraphDeploymentID, _attestationData ); return disputeID; } /** * @dev Create an indexing dispute for the arbitrator to resolve. * The disputes are created in reference to an allocationID * This function is called by a challenger that will need to `_deposit` at * least `minimumDeposit` GRT tokens. * @param _allocationID The allocation to dispute * @param _deposit Amount of tokens staked as deposit */ function createIndexingDispute(address _allocationID, uint256 _deposit) external override returns (bytes32) { // Get funds from submitter _pullSubmitterDeposit(_deposit); // Create a dispute return _createIndexingDisputeWithAllocation(msg.sender, _deposit, _allocationID); } /** * @dev Create indexing dispute internal function. * @param _fisherman The challenger creating the dispute * @param _deposit Amount of tokens staked as deposit * @param _allocationID Allocation disputed */ function _createIndexingDisputeWithAllocation( address _fisherman, uint256 _deposit, address _allocationID ) private returns (bytes32) { // Create a disputeID bytes32 disputeID = keccak256(abi.encodePacked(_allocationID)); // Only one dispute for an allocationID at a time require(!isDisputeCreated(disputeID), "Dispute already created"); // Allocation must exist IStaking.Allocation memory alloc = staking().getAllocation(_allocationID); require(alloc.indexer != address(0), "Dispute allocation must exist"); // The indexer must be disputable require(staking().hasStake(alloc.indexer), "Dispute indexer has no stake"); // Store dispute disputes[disputeID] = Dispute(alloc.indexer, _fisherman, _deposit, 0); emit IndexingDisputeCreated(disputeID, alloc.indexer, _fisherman, _deposit, _allocationID); return disputeID; } /** * @dev The arbitrator accepts a dispute as being valid. * @notice Accept a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be accepted */ function acceptDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Slash uint256 tokensToReward = _slashIndexer(dispute.indexer, dispute.fisherman); // Give the fisherman their deposit back if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeAccepted( _disputeID, dispute.indexer, dispute.fisherman, dispute.deposit.add(tokensToReward) ); } /** * @dev The arbitrator rejects a dispute as being invalid. * @notice Reject a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be rejected */ function rejectDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Handle conflicting dispute if any require( !_isDisputeInConflict(dispute), "Dispute for conflicting attestation, must accept the related ID to reject" ); // Burn the fisherman's deposit if (dispute.deposit > 0) { graphToken().burn(dispute.deposit); } emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev The arbitrator draws dispute. * @notice Ignore a dispute with ID `_disputeID` * @param _disputeID ID of the dispute to be disregarded */ function drawDispute(bytes32 _disputeID) external override onlyArbitrator { Dispute memory dispute = _resolveDispute(_disputeID); // Return deposit to the fisherman if (dispute.deposit > 0) { require( graphToken().transfer(dispute.fisherman, dispute.deposit), "Error sending dispute deposit" ); } // Resolve the conflicting dispute if any _resolveDisputeInConflict(dispute); emit DisputeDrawn(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit); } /** * @dev Resolve a dispute by removing it from storage and returning a memory copy. * @param _disputeID ID of the dispute to resolve * @return Dispute */ function _resolveDispute(bytes32 _disputeID) private returns (Dispute memory) { require(isDisputeCreated(_disputeID), "Dispute does not exist"); Dispute memory dispute = disputes[_disputeID]; // Resolve dispute delete disputes[_disputeID]; // Re-entrancy return dispute; } /** * @dev Returns whether the dispute is for a conflicting attestation or not. * @param _dispute Dispute * @return True conflicting attestation dispute */ function _isDisputeInConflict(Dispute memory _dispute) private pure returns (bool) { return _dispute.relatedDisputeID != 0; } /** * @dev Resolve the conflicting dispute if there is any for the one passed to this function. * @param _dispute Dispute * @return True if resolved */ function _resolveDisputeInConflict(Dispute memory _dispute) private returns (bool) { if (_isDisputeInConflict(_dispute)) { bytes32 relatedDisputeID = _dispute.relatedDisputeID; delete disputes[relatedDisputeID]; return true; } return false; } /** * @dev Pull deposit from submitter account. * @param _deposit Amount of tokens to deposit */ function _pullSubmitterDeposit(uint256 _deposit) private { // Ensure that fisherman has staked at least the minimum amount require(_deposit >= minimumDeposit, "Dispute deposit is under minimum required"); // Transfer tokens to deposit from fisherman to this contract require( graphToken().transferFrom(msg.sender, address(this), _deposit), "Cannot transfer tokens to deposit" ); } /** * @dev Make the staking contract slash the indexer and reward the challenger. * Give the challenger a reward equal to the fishermanRewardPercentage of slashed amount * @param _indexer Address of the indexer * @param _challenger Address of the challenger * @return Dispute reward tokens */ function _slashIndexer(address _indexer, address _challenger) private returns (uint256) { // Have staking contract slash the indexer and reward the fisherman // Give the fisherman a reward equal to the fishermanRewardPercentage of slashed amount uint256 tokensToSlash = getTokensToSlash(_indexer); uint256 tokensToReward = getTokensToReward(_indexer); require(tokensToSlash > 0, "Dispute has zero tokens to slash"); staking().slash(_indexer, tokensToSlash, tokensToReward, _challenger); return tokensToReward; } /** * @dev Recover the signer address of the `_attestation`. * @param _attestation The attestation struct * @return Signer address */ function _recoverAttestationSigner(Attestation memory _attestation) private view returns (address) { // Obtain the hash of the fully-encoded message, per EIP-712 encoding Receipt memory receipt = Receipt( _attestation.requestCID, _attestation.responseCID, _attestation.subgraphDeploymentID ); bytes32 messageHash = encodeHashReceipt(receipt); // Obtain the signer of the fully-encoded EIP-712 message hash // NOTE: The signer of the attestation is the indexer that served the request return ECDSA.recover( messageHash, abi.encodePacked(_attestation.r, _attestation.s, _attestation.v) ); } /** * @dev Get the running network chain ID * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Parse the bytes attestation into a struct from `_data`. * @return Attestation struct */ function _parseAttestation(bytes memory _data) private pure returns (Attestation memory) { // Check attestation data length require(_data.length == ATTESTATION_SIZE_BYTES, "Attestation must be 161 bytes long"); // Decode receipt (bytes32 requestCID, bytes32 responseCID, bytes32 subgraphDeploymentID) = abi.decode( _data, (bytes32, bytes32, bytes32) ); // Decode signature // Signature is expected to be in the order defined in the Attestation struct bytes32 r = _toBytes32(_data, SIG_R_OFFSET); bytes32 s = _toBytes32(_data, SIG_S_OFFSET); uint8 v = _toUint8(_data, SIG_V_OFFSET); return Attestation(requestCID, responseCID, subgraphDeploymentID, r, s, v); } /** * @dev Parse a uint8 from `_bytes` starting at offset `_start`. * @return uint8 value */ function _toUint8(bytes memory _bytes, uint256 _start) private pure returns (uint8) { require(_bytes.length >= (_start + UINT8_BYTE_LENGTH), "Bytes: out of bounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } /** * @dev Parse a bytes32 from `_bytes` starting at offset `_start`. * @return bytes32 value */ function _toBytes32(bytes memory _bytes, uint256 _start) private pure returns (bytes32) { require(_bytes.length >= (_start + BYTES32_BYTE_LENGTH), "Bytes: out of bounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } }
* @dev Return whether a dispute exists or not. @notice Return if dispute with ID `_disputeID` exists @param _disputeID True if dispute already exists/
function isDisputeCreated(bytes32 _disputeID) public override view returns (bool) { return disputes[_disputeID].fisherman != address(0); }
908,953
[ 1, 990, 2856, 279, 1015, 2507, 1704, 578, 486, 18, 225, 2000, 309, 1015, 2507, 598, 1599, 1375, 67, 2251, 2507, 734, 68, 1704, 225, 389, 2251, 2507, 734, 1053, 309, 1015, 2507, 1818, 1704, 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, 353, 1669, 2507, 6119, 12, 3890, 1578, 389, 2251, 2507, 734, 13, 1071, 3849, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1015, 458, 281, 63, 67, 2251, 2507, 734, 8009, 22905, 29650, 480, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.22 <0.7.0; /** * @title Payments. Management of payments * @dev Provide functions for payment and withdraw of funds. Stores payments. */ contract Payments { address payable owner; struct Payment { string id; uint256 amount; uint256 date; } // Log of payments mapping(address=>Payment[]) private payments; // Event to notify payments event Pay(address, string, uint); constructor() public { owner = msg.sender; } // Optional. Fallback function to receive funds function() external payable { require (msg.data.length == 0, 'The called function does not exist'); } /** * @dev `pay` Payment in wei * Emits `Pay` on success with payer account, purchase reference and amount. * @param id Reference of the purchase * @param value Amount in wei of the payment */ function pay(string memory id, uint value) public payable { require(msg.value == value, 'The payment does not match the value of the transaction'); payments[msg.sender].push(Payment(id, msg.value, block.timestamp)); emit Pay(msg.sender, id, msg.value); } /** * @dev `withdraw` Withdraw funds to the owner of the contract */ function withdraw() public payable { require(msg.sender == owner, 'Only owner can withdraw funds'); owner.transfer(address(this).balance); } /** * @dev `paymentsOf` Number of payments made by an account * @param buyer Account or address * @return number of payments */ function paymentsOf(address buyer) public view returns (uint) { return payments[buyer].length; } /** * @dev `paymentOfAt` Returns the detail of a payment of an account * @param buyer Account or addres * @param index Index of the payment * @return {0: "Purchase reference", 1: "Payment amount", 2: "Payment date"} */ function paymentOfAt(address buyer, uint256 index) public view returns (string memory, uint256 amount, uint256 date) { Payment[] memory pays = payments[buyer]; require(pays.length > index, "Payment does not exist"); Payment memory payment = pays[index]; return (payment.id, payment.amount, payment.date); } }
* @dev `withdraw` Withdraw funds to the owner of the contract/
function withdraw() public payable { require(msg.sender == owner, 'Only owner can withdraw funds'); owner.transfer(address(this).balance); }
5,466,322
[ 1, 68, 1918, 9446, 68, 3423, 9446, 284, 19156, 358, 326, 3410, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 296, 3386, 3410, 848, 598, 9446, 284, 19156, 8284, 203, 3639, 3410, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 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 ]
./full_match/43114/0xDb69C8841363D76efc0B7008AfaC15756C8BF443/sources/contracts/MasterChefJoeV3.sol
@notice The (older) MasterChefJoeV2 contract gives out a constant number of JOE tokens per block. It is the only address with minting rights for JOE. The idea for this MasterChefJoeV3 (MCJV3) contract is therefore to be the owner of a dummy token that is deposited into the MasterChefJoeV2 (MCJV2) contract. The allocation point for this pool on MCJV3 is the total allocation point for all pools that receive double incentives.
contract MasterChefJoeV3 is Ownable, ReentrancyGuard { using SafeMath for uint256; using BoringERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; struct UserInfo { uint256 amount; uint256 rewardDebt; } struct PoolInfo { IERC20 lpToken; uint256 accJoePerShare; uint256 lastRewardTimestamp; uint256 allocPoint; IRewarder rewarder; } uint256 private constant ACC_TOKEN_PRECISION = 1e18; event Add(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event Set(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event UpdatePool(uint256 indexed pid, uint256 lastRewardTimestamp, uint256 lpSupply, uint256 accJoePerShare); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Init(); IMasterChef _MASTER_CHEF_V2, IERC20 _joe, uint256 _MASTER_PID IMasterChef public immutable MASTER_CHEF_V2; IERC20 public immutable JOE; uint256 public immutable MASTER_PID; PoolInfo[] public poolInfo; EnumerableSet.AddressSet private lpTokens; mapping(uint256 => mapping(address => UserInfo)) public userInfo; uint256 public totalAllocPoint; constructor( ) public { MASTER_CHEF_V2 = _MASTER_CHEF_V2; JOE = _joe; MASTER_PID = _MASTER_PID; } function init(IERC20 dummyToken) external onlyOwner { uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "MasterChefV2: Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(address(MASTER_CHEF_V2), balance); MASTER_CHEF_V2.deposit(MASTER_PID, balance); emit Init(); } function poolLength() external view returns (uint256 pools) { pools = poolInfo.length; } function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) external onlyOwner { require(!lpTokens.contains(address(_lpToken)), "add: LP already added"); _lpToken.balanceOf(address(this)); uint256 lastRewardTimestamp = block.timestamp; totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: allocPoint, lastRewardTimestamp: lastRewardTimestamp, accJoePerShare: 0, rewarder: _rewarder }) ); lpTokens.add(address(_lpToken)); emit Add(poolInfo.length.sub(1), allocPoint, _lpToken, _rewarder); } function add( uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder ) external onlyOwner { require(!lpTokens.contains(address(_lpToken)), "add: LP already added"); _lpToken.balanceOf(address(this)); uint256 lastRewardTimestamp = block.timestamp; totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: allocPoint, lastRewardTimestamp: lastRewardTimestamp, accJoePerShare: 0, rewarder: _rewarder }) ); lpTokens.add(address(_lpToken)); emit Add(poolInfo.length.sub(1), allocPoint, _lpToken, _rewarder); } function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) external onlyOwner { PoolInfo memory pool = poolInfo[_pid]; totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); pool.allocPoint = _allocPoint; if (overwrite) { pool.rewarder = _rewarder; } poolInfo[_pid] = pool; emit Set(_pid, _allocPoint, overwrite ? _rewarder : pool.rewarder, overwrite); } function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite ) external onlyOwner { PoolInfo memory pool = poolInfo[_pid]; totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); pool.allocPoint = _allocPoint; if (overwrite) { pool.rewarder = _rewarder; } poolInfo[_pid] = pool; emit Set(_pid, _allocPoint, overwrite ? _rewarder : pool.rewarder, overwrite); } function pendingTokens(uint256 _pid, address _user) external view returns ( uint256 pendingJoe, address bonusTokenAddress, string memory bonusTokenSymbol, uint256 pendingBonusToken ) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJoePerShare = pool.accJoePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); accJoePerShare = accJoePerShare.add(joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply)); } pendingJoe = user.amount.mul(accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); if (address(pool.rewarder) != address(0)) { bonusTokenAddress = address(pool.rewarder.rewardToken()); bonusTokenSymbol = IERC20(pool.rewarder.rewardToken()).safeSymbol(); pendingBonusToken = pool.rewarder.pendingTokens(_user); } } function pendingTokens(uint256 _pid, address _user) external view returns ( uint256 pendingJoe, address bonusTokenAddress, string memory bonusTokenSymbol, uint256 pendingBonusToken ) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJoePerShare = pool.accJoePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); accJoePerShare = accJoePerShare.add(joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply)); } pendingJoe = user.amount.mul(accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); if (address(pool.rewarder) != address(0)) { bonusTokenAddress = address(pool.rewarder.rewardToken()); bonusTokenSymbol = IERC20(pool.rewarder.rewardToken()).safeSymbol(); pendingBonusToken = pool.rewarder.pendingTokens(_user); } } function pendingTokens(uint256 _pid, address _user) external view returns ( uint256 pendingJoe, address bonusTokenAddress, string memory bonusTokenSymbol, uint256 pendingBonusToken ) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJoePerShare = pool.accJoePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); accJoePerShare = accJoePerShare.add(joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply)); } pendingJoe = user.amount.mul(accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); if (address(pool.rewarder) != address(0)) { bonusTokenAddress = address(pool.rewarder.rewardToken()); bonusTokenSymbol = IERC20(pool.rewarder.rewardToken()).safeSymbol(); pendingBonusToken = pool.rewarder.pendingTokens(_user); } } function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } function joePerSec() public view returns (uint256 amount) { uint256 total = 1000; uint256 lpPercent = total.sub( MASTER_CHEF_V2.devPercent().sub(MASTER_CHEF_V2.treasuryPercent().sub(MASTER_CHEF_V2.investorPercent())) ); uint256 lpShare = MASTER_CHEF_V2.joePerSec().mul(lpPercent).div(total); amount = lpShare.mul(MASTER_CHEF_V2.poolInfo(MASTER_PID).allocPoint).div(MASTER_CHEF_V2.totalAllocPoint()); } function updatePool(uint256 pid) public { PoolInfo memory pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTimestamp) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply > 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoePerShare = pool.accJoePerShare.add((joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply))); } pool.lastRewardTimestamp = block.timestamp; poolInfo[pid] = pool; emit UpdatePool(pid, pool.lastRewardTimestamp, lpSupply, pool.accJoePerShare); } } function updatePool(uint256 pid) public { PoolInfo memory pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTimestamp) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply > 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoePerShare = pool.accJoePerShare.add((joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply))); } pool.lastRewardTimestamp = block.timestamp; poolInfo[pid] = pool; emit UpdatePool(pid, pool.lastRewardTimestamp, lpSupply, pool.accJoePerShare); } } function updatePool(uint256 pid) public { PoolInfo memory pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTimestamp) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply > 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoePerShare = pool.accJoePerShare.add((joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply))); } pool.lastRewardTimestamp = block.timestamp; poolInfo[pid] = pool; emit UpdatePool(pid, pool.lastRewardTimestamp, lpSupply, pool.accJoePerShare); } } function deposit(uint256 pid, uint256 amount) external nonReentrant { harvestFromMasterChef(); updatePool(pid); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, pid, pending); } uint256 balanceBefore = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), amount); uint256 receivedAmount = pool.lpToken.balanceOf(address(this)).sub(balanceBefore); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } emit Deposit(msg.sender, pid, amount); } function deposit(uint256 pid, uint256 amount) external nonReentrant { harvestFromMasterChef(); updatePool(pid); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, pid, pending); } uint256 balanceBefore = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), amount); uint256 receivedAmount = pool.lpToken.balanceOf(address(this)).sub(balanceBefore); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } emit Deposit(msg.sender, pid, amount); } user.amount = user.amount.add(receivedAmount); IRewarder _rewarder = pool.rewarder; function deposit(uint256 pid, uint256 amount) external nonReentrant { harvestFromMasterChef(); updatePool(pid); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, pid, pending); } uint256 balanceBefore = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), amount); uint256 receivedAmount = pool.lpToken.balanceOf(address(this)).sub(balanceBefore); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } emit Deposit(msg.sender, pid, amount); } function withdraw(uint256 pid, uint256 amount) external nonReentrant { harvestFromMasterChef(); updatePool(pid); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, pid, pending); } user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } pool.lpToken.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } function withdraw(uint256 pid, uint256 amount) external nonReentrant { harvestFromMasterChef(); updatePool(pid); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, pid, pending); } user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } pool.lpToken.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } user.amount = user.amount.sub(amount); IRewarder _rewarder = pool.rewarder; function withdraw(uint256 pid, uint256 amount) external nonReentrant { harvestFromMasterChef(); updatePool(pid); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt); JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, pid, pending); } user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } pool.lpToken.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } function harvestFromMasterChef() public { MASTER_CHEF_V2.deposit(MASTER_PID, 0); } function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = pool.rewarder; if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, 0); } emit EmergencyWithdraw(msg.sender, pid, amount); } function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = pool.rewarder; if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, 0); } emit EmergencyWithdraw(msg.sender, pid, amount); } pool.lpToken.safeTransfer(msg.sender, amount); }
4,539,710
[ 1, 1986, 261, 1498, 13, 13453, 39, 580, 74, 46, 15548, 58, 22, 6835, 14758, 596, 279, 5381, 1300, 434, 804, 51, 41, 2430, 1534, 1203, 18, 2597, 353, 326, 1338, 1758, 598, 312, 474, 310, 14989, 364, 804, 51, 41, 18, 1021, 21463, 364, 333, 13453, 39, 580, 74, 46, 15548, 58, 23, 261, 20022, 46, 58, 23, 13, 6835, 353, 13526, 358, 506, 326, 3410, 434, 279, 9609, 1147, 716, 353, 443, 1724, 329, 1368, 326, 13453, 39, 580, 74, 46, 15548, 58, 22, 261, 20022, 46, 58, 22, 13, 6835, 18, 1021, 13481, 1634, 364, 333, 2845, 603, 24105, 46, 58, 23, 353, 326, 2078, 13481, 1634, 364, 777, 16000, 716, 6798, 1645, 316, 2998, 3606, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13453, 39, 580, 74, 46, 15548, 58, 23, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 605, 6053, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 565, 1958, 25003, 288, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 19890, 758, 23602, 31, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 3639, 467, 654, 39, 3462, 12423, 1345, 31, 203, 3639, 2254, 5034, 4078, 46, 15548, 2173, 9535, 31, 203, 3639, 2254, 5034, 1142, 17631, 1060, 4921, 31, 203, 3639, 2254, 5034, 4767, 2148, 31, 203, 3639, 15908, 359, 297, 765, 283, 20099, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 3238, 5381, 18816, 67, 8412, 67, 3670, 26913, 273, 404, 73, 2643, 31, 203, 203, 565, 871, 1436, 12, 11890, 5034, 8808, 4231, 16, 2254, 5034, 4767, 2148, 16, 467, 654, 39, 3462, 8808, 12423, 1345, 16, 15908, 359, 297, 765, 8808, 283, 20099, 1769, 203, 565, 871, 1000, 12, 11890, 5034, 8808, 4231, 16, 2254, 5034, 4767, 2148, 16, 15908, 359, 297, 765, 8808, 283, 20099, 16, 1426, 6156, 1769, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 2315, 2864, 12, 11890, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-01-13 */ // File: contracts/loopring/impl/BrokerData.sol pragma solidity 0.5.7; library BrokerData { struct BrokerOrder { address owner; bytes32 orderHash; uint fillAmountB; uint requestedAmountS; uint requestedFeeAmount; address tokenRecipient; bytes extraData; } struct BrokerApprovalRequest { BrokerOrder[] orders; address tokenS; address tokenB; address feeToken; uint totalFillAmountB; uint totalRequestedAmountS; uint totalRequestedFeeAmount; } struct BrokerInterceptorReport { address owner; address broker; bytes32 orderHash; address tokenB; address tokenS; address feeToken; uint fillAmountB; uint spentAmountS; uint spentFeeAmount; address tokenRecipient; bytes extraData; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @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: contracts/market-making/sources/ERC20.sol contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); uint256 internal _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: contracts/market-making/sources/uniswap/UniswapExchange.sol pragma solidity ^0.5.0; interface IUniswapFactory { event NewExchange(address indexed token, address indexed exchange); function initializeFactory(address template) external; function createExchange(address token) external returns (address payable); function getExchange(address token) external view returns (address payable); function getToken(address token) external view returns (address); function getTokenWihId(uint256 token_id) external view returns (address); } interface IUniswapExchange { event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); function () external payable; function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256); function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256); function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256); function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256); function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256); function tokenAddress() external view returns (address); function factoryAddress() external view returns (address); function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); } contract UniswapExchange is ERC20 { /***********************************| | Variables && Events | |__________________________________*/ // Variables bytes32 public name; // Uniswap V1 bytes32 public symbol; // UNI-V1 uint256 public decimals; // 18 ERC20 token; // address of the ERC20 token traded on this contract IUniswapFactory factory; // interface for the factory that created this contract // Events event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); /***********************************| | Constsructor | |__________________________________*/ /** * @dev This function acts as a contract constructor which is not currently supported in contracts deployed * using create_with_code_of(). It is called once by the factory during contract creation. */ function setup(address token_addr) public { require( address(factory) == address(0) && address(token) == address(0) && token_addr != address(0), "INVALID_ADDRESS" ); factory = IUniswapFactory(msg.sender); token = ERC20(token_addr); name = 0x556e697377617020563100000000000000000000000000000000000000000000; symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000; decimals = 18; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value). * @dev User cannot specify minimum output or deadline. */ function () external payable { ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender); } /** * @dev Pricing function for converting between ETH && Tokens. * @param input_amount Amount of ETH or Tokens being sold. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens bought. */ function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0, "INVALID_VALUE"); uint256 input_amount_with_fee = input_amount.mul(997); uint256 numerator = input_amount_with_fee.mul(output_reserve); uint256 denominator = input_reserve.mul(1000).add(input_amount_with_fee); return numerator / denominator; } /** * @dev Pricing function for converting between ETH && Tokens. * @param output_amount Amount of ETH or Tokens being bought. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens sold. */ function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0); uint256 numerator = input_reserve.mul(output_amount).mul(1000); uint256 denominator = (output_reserve.sub(output_amount)).mul(997); return (numerator / denominator).add(1); } function ethToTokenInput(uint256 eth_sold, uint256 min_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_sold > 0 && min_tokens > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = getInputPrice(eth_sold, address(this).balance.sub(eth_sold), token_reserve); require(tokens_bought >= min_tokens); require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return tokens_bought; } /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value) && minimum output. * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens bought. */ function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) public payable returns (uint256) { return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies exact input (msg.value) && minimum output * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of Tokens bought. */ function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) public payable returns(uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient); } function ethToTokenOutput(uint256 tokens_bought, uint256 max_eth, uint256 deadline, address payable buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_bought > 0 && max_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance.sub(max_eth), token_reserve); // Throws if eth_sold > max_eth uint256 eth_refund = max_eth.sub(eth_sold); if (eth_refund > 0) { buyer.transfer(eth_refund); } require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return eth_sold; } /** * @notice Convert ETH to Tokens. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH sold. */ function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) public payable returns(uint256) { return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of ETH sold. */ function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) public payable returns (uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient); } function tokenToEthInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth); recipient.transfer(wei_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, wei_bought); return wei_bought; } /** * @notice Convert Tokens to ETH. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH bought. */ function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) public returns (uint256) { return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of ETH bought. */ function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient); } function tokenToEthOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens >= tokens_sold); recipient.transfer(eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens to ETH. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens sold. */ function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) public returns (uint256) { return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of Tokens sold. */ function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient); } function tokenToTokenInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_tokens_bought > 0 && min_eth_bought > 0); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 tokens_bought = IUniswapExchange(exchange_addr).ethToTokenTransferInput.value(wei_bought)(min_tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, wei_bought); return tokens_bought; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } function tokenToTokenOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && (tokens_bought > 0 && max_eth_sold > 0)); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 eth_bought = IUniswapExchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens_sold >= tokens_sold && max_eth_sold >= eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 eth_sold = IUniswapExchange(exchange_addr).ethToTokenTransferOutput.value(eth_bought)(tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Public price function for ETH to Token trades with an exact input. * @param eth_sold Amount of ETH sold. * @return Amount of Tokens that can be bought with input ETH. */ function getEthToTokenInputPrice(uint256 eth_sold) public view returns (uint256) { require(eth_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); return getInputPrice(eth_sold, address(this).balance, token_reserve); } /** * @notice Public price function for ETH to Token trades with an exact output. * @param tokens_bought Amount of Tokens bought. * @return Amount of ETH needed to buy output Tokens. */ function getEthToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) { require(tokens_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve); return eth_sold; } /** * @notice Public price function for Token to ETH trades with an exact input. * @param tokens_sold Amount of Tokens sold. * @return Amount of ETH that can be bought with input Tokens. */ function getTokenToEthInputPrice(uint256 tokens_sold) public view returns (uint256) { require(tokens_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); return eth_bought; } /** * @notice Public price function for Token to ETH trades with an exact output. * @param eth_bought Amount of output ETH. * @return Amount of Tokens needed to buy output ETH. */ function getTokenToEthOutputPrice(uint256 eth_bought) public view returns (uint256) { require(eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); return getOutputPrice(eth_bought, token_reserve, address(this).balance); } /** * @return Address of Token that is sold on this exchange. */ function tokenAddress() public view returns (address) { return address(token); } /** * @return Address of factory that created this exchange. */ function factoryAddress() public view returns (address) { return address(factory); } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit ETH && Tokens (token) at current ratio to mint UNI tokens. * @dev min_liquidity does nothing when total UNI supply is 0. * @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0. * @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of UNI minted. */ function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) public payable returns (uint256) { require(deadline > block.timestamp && max_tokens > 0 && msg.value > 0, 'UniswapExchange#addLiquidity: INVALID_ARGUMENT'); uint256 total_liquidity = _totalSupply; if (total_liquidity > 0) { require(min_liquidity > 0); uint256 eth_reserve = address(this).balance.sub(msg.value); uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = (msg.value.mul(token_reserve) / eth_reserve).add(1); uint256 liquidity_minted = msg.value.mul(total_liquidity) / eth_reserve; require(max_tokens >= token_amount && liquidity_minted >= min_liquidity); _balances[msg.sender] = _balances[msg.sender].add(liquidity_minted); _totalSupply = total_liquidity.add(liquidity_minted); require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, liquidity_minted); return liquidity_minted; } else { require(address(factory) != address(0) && address(token) != address(0) && msg.value >= 1000000000, "INVALID_VALUE"); require(factory.getExchange(address(token)) == address(this)); uint256 token_amount = max_tokens; uint256 initial_liquidity = address(this).balance; _totalSupply = initial_liquidity; _balances[msg.sender] = initial_liquidity; require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, initial_liquidity); return initial_liquidity; } } /** * @dev Burn UNI tokens to withdraw ETH && Tokens at current ratio. * @param amount Amount of UNI burned. * @param min_eth Minimum ETH withdrawn. * @param min_tokens Minimum Tokens withdrawn. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of ETH && Tokens withdrawn. */ function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) public returns (uint256, uint256) { require(amount > 0 && deadline > block.timestamp && min_eth > 0 && min_tokens > 0); uint256 total_liquidity = _totalSupply; require(total_liquidity > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = amount.mul(address(this).balance) / total_liquidity; uint256 token_amount = amount.mul(token_reserve) / total_liquidity; require(eth_amount >= min_eth && token_amount >= min_tokens); _balances[msg.sender] = _balances[msg.sender].sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW _totalSupply = total_liquidity.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW msg.sender.transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); emit RemoveLiquidity(msg.sender, eth_amount, token_amount); emit Transfer(msg.sender, address(0), amount); return (eth_amount, token_amount); } } // File: contracts/market-making/sources/WETH.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; contract WETH { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom(address src, address dst, uint wad) public returns (bool); function deposit() public payable; function withdraw(uint wad) public; } // File: contracts/loopring/iface/IBrokerDelegate.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; /** * @title IBrokerDelegate * @author Zack Rubenstein */ interface IBrokerDelegate { /* * Loopring requests an allowance be set on a given token for a specified amount. Order details * are provided (tokenS, totalAmountS, tokenB, totalAmountB, orderTokenRecipient, extraOrderData) * to aid in any calculations or on-chain exchange of assets that may be required. The last 4 * parameters concern the actual token approval being requested of the broker. * * @returns Whether or not onOrderFillReport should be called for orders using this broker */ function brokerRequestAllowance(BrokerData.BrokerApprovalRequest calldata request) external returns (bool); /* * After Loopring performs all of the transfers necessary to complete all the submitted * rings it will call this function for every order's brokerInterceptor (if set) passing * along the final fill counts for tokenB, tokenS and feeToken. This allows actions to be * performed on a per-order basis after all tokenS/feeToken funds have left the order owner's * possession and the tokenB funds have been transferred to the order owner's intended recipient */ function onOrderFillReport(BrokerData.BrokerInterceptorReport calldata fillReport) external; /* * Get the available token balance controlled by the broker on behalf of an address (owner) */ function brokerBalanceOf(address owner, address token) external view returns (uint); } // File: contracts/dolomite-direct/DolomiteDirectV1.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7;interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; } library Types { struct RequestFee { address feeRecipient; address feeToken; uint feeAmount; } struct RequestSignature { uint8 v; bytes32 r; bytes32 s; } enum RequestType { Update, Transfer, Approve, Perform } struct Request { address owner; address target; RequestType requestType; bytes payload; uint nonce; RequestFee fee; RequestSignature signature; } struct TransferRequest { address token; address recipient; uint amount; bool unwrap; } } interface IDolomiteMarginTradingBroker { function brokerMarginRequestApproval(address owner, address token, uint amount) external; function brokerMarginGetTrader(address owner, bytes calldata orderData) external view returns (address); } interface IVersionable { /* * Is called by IDepositContractRegistry when this version * is being upgraded to. Will call `versionEndUsage` on the * old contract before calling this one */ function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external; /* * Is called by IDepositContractRegistry when this version is * being upgraded from. IDepositContractRegistry will then call * `versionBeginUsage` on the new contract */ function versionEndUsage( address owner, address payable depositAddress, address newVersion, bytes calldata additionalData ) external; } interface IDepositContract { function perform( address addr, string calldata signature, bytes calldata encodedParams, uint value ) external returns (bytes memory); } interface IDepositContractRegistry { function depositAddressOf(address owner) external view returns (address payable); function operatorOf(address owner, address operator) external returns (bool); } library DepositContractHelper { function wrapAndTransferToken(IDepositContract self, address token, address recipient, uint amount, address wethAddress) internal { if (token == wethAddress) { uint etherBalance = address(self).balance; if (etherBalance > 0) wrapEth(self, token, etherBalance); } transferToken(self, token, recipient, amount); } function transferToken(IDepositContract self, address token, address recipient, uint amount) internal { self.perform(token, "transfer(address,uint256)", abi.encode(recipient, amount), 0); } function transferEth(IDepositContract self, address recipient, uint amount) internal { self.perform(recipient, "", abi.encode(), amount); } function approveToken(IDepositContract self, address token, address broker, uint amount) internal { self.perform(token, "approve(address,uint256)", abi.encode(broker, amount), 0); } function wrapEth(IDepositContract self, address wethToken, uint amount) internal { self.perform(wethToken, "deposit()", abi.encode(), amount); } function unwrapWeth(IDepositContract self, address wethToken, uint amount) internal { self.perform(wethToken, "withdraw(uint256)", abi.encode(amount), 0); } function setDydxOperator(IDepositContract self, address dydxContract, address operator) internal { bytes memory encodedParams = abi.encode( bytes32(0x0000000000000000000000000000000000000000000000000000000000000020), bytes32(0x0000000000000000000000000000000000000000000000000000000000000001), operator, bytes32(0x0000000000000000000000000000000000000000000000000000000000000001) ); self.perform(dydxContract, "setOperators((address,bool)[])", encodedParams, 0); } } library RequestHelper { bytes constant personalPrefix = "\x19Ethereum Signed Message:\n32"; function getSigner(Types.Request memory self) internal pure returns (address) { bytes32 messageHash = keccak256(abi.encode( self.owner, self.target, self.requestType, self.payload, self.nonce, abi.encode(self.fee.feeRecipient, self.fee.feeToken, self.fee.feeAmount) )); bytes32 prefixedHash = keccak256(abi.encodePacked(personalPrefix, messageHash)); return ecrecover(prefixedHash, self.signature.v, self.signature.r, self.signature.s); } function decodeTransferRequest(Types.Request memory self) internal pure returns (Types.TransferRequest memory transferRequest) { require(self.requestType == Types.RequestType.Transfer, "INVALID_REQUEST_TYPE"); ( transferRequest.token, transferRequest.recipient, transferRequest.amount, transferRequest.unwrap ) = abi.decode(self.payload, (address, address, uint, bool)); } } contract Requestable { using RequestHelper for Types.Request; mapping(address => uint) nonces; function validateRequest(Types.Request memory request) internal { require(request.target == address(this), "INVALID_TARGET"); require(request.getSigner() == request.owner, "INVALID_SIGNATURE"); require(nonces[request.owner] + 1 == request.nonce, "INVALID_NONCE"); if (request.fee.feeAmount > 0) { require(balanceOf(request.owner, request.fee.feeToken) >= request.fee.feeAmount, "INSUFFICIENT_FEE_BALANCE"); } nonces[request.owner] += 1; } function completeRequest(Types.Request memory request) internal { if (request.fee.feeAmount > 0) { _payRequestFee(request.owner, request.fee.feeToken, request.fee.feeRecipient, request.fee.feeAmount); } } function nonceOf(address owner) public view returns (uint) { return nonces[owner]; } // Abtract functions function balanceOf(address owner, address token) public view returns (uint); function _payRequestFee(address owner, address feeToken, address feeRecipient, uint feeAmount) internal; } /** * @title DolomiteDirectV1 * @author Zack Rubenstein * * Interfaces with the IDepositContractRegistry and individual * IDepositContracts to enable smart-wallet functionality as well * as spot and margin trading on Dolomite (through Loopring & dYdX) */ contract DolomiteDirectV1 is Requestable, IVersionable, IDolomiteMarginTradingBroker { using DepositContractHelper for IDepositContract; using SafeMath for uint; IDepositContractRegistry public registry; address public loopringDelegate; address public dolomiteMarginProtocolAddress; address public dydxProtocolAddress; address public wethTokenAddress; constructor( address _depositContractRegistry, address _loopringDelegate, address _dolomiteMarginProtocol, address _dydxProtocolAddress, address _wethTokenAddress ) public { registry = IDepositContractRegistry(_depositContractRegistry); loopringDelegate = _loopringDelegate; dolomiteMarginProtocolAddress = _dolomiteMarginProtocol; dydxProtocolAddress = _dydxProtocolAddress; wethTokenAddress = _wethTokenAddress; } /* * Returns the available balance for an owner that this contract manages. * If the token is WETH, it returns the sum of the ETH and WETH balance, * as ETH is automatically wrapped upon transfers (unless the unwrap option is * set to true in the transfer request) */ function balanceOf(address owner, address token) public view returns (uint) { address depositAddress = registry.depositAddressOf(owner); uint tokenBalance = IERC20(token).balanceOf(depositAddress); if (token == wethTokenAddress) tokenBalance = tokenBalance.add(depositAddress.balance); return tokenBalance; } /* * Send up a signed transfer request and the given amount tokens * is transfered to the specified recipient. */ function transfer(Types.Request memory request) public { validateRequest(request); Types.TransferRequest memory transferRequest = request.decodeTransferRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); _transfer( transferRequest.token, depositAddress, transferRequest.recipient, transferRequest.amount, transferRequest.unwrap ); completeRequest(request); } // ============================= function _transfer(address token, address payable depositAddress, address recipient, uint amount, bool unwrap) internal { IDepositContract depositContract = IDepositContract(depositAddress); if (token == wethTokenAddress && unwrap) { if (depositAddress.balance < amount) { depositContract.unwrapWeth(wethTokenAddress, amount.sub(depositAddress.balance)); } depositContract.transferEth(recipient, amount); return; } depositContract.wrapAndTransferToken(token, recipient, amount, wethTokenAddress); } // ----------------------------- // Loopring Broker Delegate function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) { require(msg.sender == loopringDelegate); BrokerData.BrokerOrder[] memory mergedOrders = new BrokerData.BrokerOrder[](request.orders.length); uint numMergedOrders = 1; mergedOrders[0] = request.orders[0]; if (request.orders.length > 1) { for (uint i = 1; i < request.orders.length; i++) { bool isDuplicate = false; for (uint b = 0; b < numMergedOrders; b++) { if (request.orders[i].owner == mergedOrders[b].owner) { mergedOrders[b].requestedAmountS += request.orders[i].requestedAmountS; mergedOrders[b].requestedFeeAmount += request.orders[i].requestedFeeAmount; isDuplicate = true; break; } } if (!isDuplicate) { mergedOrders[numMergedOrders] = request.orders[i]; numMergedOrders += 1; } } } for (uint j = 0; j < numMergedOrders; j++) { BrokerData.BrokerOrder memory order = mergedOrders[j]; address payable depositAddress = registry.depositAddressOf(order.owner); _transfer(request.tokenS, depositAddress, address(this), order.requestedAmountS, false); if (order.requestedFeeAmount > 0) _transfer(request.feeToken, depositAddress, address(this), order.requestedFeeAmount, false); } return false; // Does not use onOrderFillReport } function onOrderFillReport(BrokerData.BrokerInterceptorReport memory fillReport) public { // Do nothing } function brokerBalanceOf(address owner, address tokenAddress) public view returns (uint) { return balanceOf(owner, tokenAddress); } // ---------------------------- // Dolomite Margin Trading Broker function brokerMarginRequestApproval(address owner, address token, uint amount) public { require(msg.sender == dolomiteMarginProtocolAddress); address payable depositAddress = registry.depositAddressOf(owner); _transfer(token, depositAddress, address(this), amount, false); } function brokerMarginGetTrader(address owner, bytes memory orderData) public view returns (address) { return registry.depositAddressOf(owner); } // ----------------------------- // Requestable function _payRequestFee(address owner, address feeToken, address feeRecipient, uint feeAmount) internal { _transfer(feeToken, registry.depositAddressOf(owner), feeRecipient, feeAmount, false); } // ----------------------------- // Versionable function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external { // Approve the DolomiteMarginProtocol as an operator for the deposit contract's dYdX account IDepositContract(depositAddress).setDydxOperator(dydxProtocolAddress, dolomiteMarginProtocolAddress); } function versionEndUsage( address owner, address payable depositAddress, address newVersion, bytes calldata additionalData ) external { /* do nothing */ } // ============================= // Administrative /* * Tokens are held in individual deposit contracts, the only time a trader's * funds are held by this contract is when Loopring or dYdX requests a trader's * tokens, and immediately upon this contract moving funds into itself, Loopring * or dYdX will move the funds out and into themselves. Thus, we can open this * function up for anyone to call to set or reset the approval for Loopring and * dYdX for a given token. The reason these approvals are set globally and not * on an as-needed (per fill) basis is to reduce gas costs. */ function enableTrading(address token) external { IERC20(token).approve(loopringDelegate, 10**70); IERC20(token).approve(dolomiteMarginProtocolAddress, 10**70); } } // File: contracts/market-making/helper/MakerBrokerBase.sol pragma solidity 0.5.7; contract MakerBrokerBase { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "NOT_OWNER"); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0x0), "ZERO_ADDRESS"); owner = newOwner; } function withdrawDust(address token) external { require(msg.sender == owner, "UNAUTHORIZED"); ERC20(token).transfer(msg.sender, ERC20(token).balanceOf(address(this))); } function withdrawEthDust() external { require(msg.sender == owner, "UNAUTHORIZED"); msg.sender.transfer(address(this).balance); } } // File: contracts/market-making/UniswapMakerBroker.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; library UniswapFactoryHelper { function exchangeOf(IUniswapFactory self, address token) internal returns (IUniswapExchange) { return IUniswapExchange(self.getExchange(token)); } } /* * Inherits Loopring's IBrokerDelegate and sources liquidity from Uniswap * when the Loopring protocol requests a token approval. Because the Loopring * protocol expects the taker order to precede maker orders, and non-brokered * transfers occur before before brokered transfers, it is guaranteed that this * broker contract will receive the necessary tokens to trade, right before it * sets the approval and the Loopring protocol transfers the tokens out. Thus, * liquidity can be sourced on-chain with no money down! */ contract UniswapMakerBroker is MakerBrokerBase { using UniswapFactoryHelper for IUniswapFactory; address public wethTokenAddress; address public loopringProtocol; IUniswapFactory public uniswapFactory; mapping(address => address) public tokenToExchange; mapping(address => bool) public tokenToIsSetup; constructor(address _loopringProtocol, address _uniswapFactory, address _wethTokenAddress) public { loopringProtocol = _loopringProtocol; wethTokenAddress = _wethTokenAddress; uniswapFactory = IUniswapFactory(_uniswapFactory); } function setupToken(address token, bool setupExchange) public { if (setupExchange) { IUniswapExchange exchange = uniswapFactory.exchangeOf(token); ERC20(token).approve(address(exchange), 10 ** 70); tokenToExchange[token] = address(exchange); } ERC20(token).approve(loopringProtocol, 10 ** 70); tokenToIsSetup[token] = true; } function () external payable { // No op, but accepts ETH being sent to this contract. } // -------------------------------- // Loopring Broker Delegate function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) { require(msg.sender == loopringProtocol, "Uniswap MakerBroker: Unauthorized caller"); require(tokenToIsSetup[request.tokenS], "Uniswap MakerBroker: tokenS is not setup yet"); for (uint i = 0; i < request.orders.length; i++) { require(request.orders[i].tokenRecipient == address(this), "Uniswap MakerBroker: Order tokenRecipient must be this broker"); require(request.orders[i].owner == owner, "Uniswap MakerBroker: Order owner must be the owner of this contract"); } if (request.tokenB == wethTokenAddress) { // We need to convert WETH to ETH to 1) avoid double fee payment on Uniswap and 2) get the best price on Uniswap WETH(wethTokenAddress).withdraw(request.totalFillAmountB); } // perform exchange bool isTokenBExchangeWrapper = abi.decode(request.orders[0].extraData, (bool)); IUniswapExchange exchange; if (isTokenBExchangeWrapper) { exchange = IUniswapExchange(address(uint160(tokenToExchange[request.tokenB]))); } else { exchange = IUniswapExchange(address(uint160(tokenToExchange[request.tokenS]))); } uint deadline = block.timestamp + 1; uint exchangeAmount; if (request.tokenS == wethTokenAddress) { exchangeAmount = exchange.tokenToEthSwapInput(request.totalFillAmountB, request.totalRequestedAmountS, deadline); } else if (request.tokenB == wethTokenAddress) { exchangeAmount = exchange.ethToTokenSwapInput.value(request.totalFillAmountB)(request.totalRequestedAmountS, deadline); } else { // Pure token to token address tokenToBuy; if (isTokenBExchangeWrapper) { request.tokenS; } else { request.tokenB; } exchangeAmount = exchange.tokenToTokenSwapInput( request.totalFillAmountB, request.totalRequestedAmountS, /* minEthBoughtInWei */ 1, // We don't care about the token <-> ETH exchange rate as long as we get enough tokenB deadline, tokenToBuy); } if (request.tokenS == wethTokenAddress) { // Orders on Dolomite require we use WETH instead of ETH, so we must convert it back WETH(wethTokenAddress).deposit.value(exchangeAmount)(); } return false; } function onOrderFillReport(BrokerData.BrokerInterceptorReport memory fillReport) public { // No op } /* * Balance is unknown as it is entirely dependent on the offer in Uniswap being filled. * Thus we send down a very large number to ensure the relay/matching engine believes * orders from this broker have enough of a balance for trades to be filled. */ function brokerBalanceOf(address owner, address tokenAddress) public view returns (uint) { return 10 ** 70; } }
* @notice Convert Tokens (token) to Tokens (token_addr). @dev User specifies exact input && minimum output. @param tokens_sold Amount of Tokens sold. @param min_tokens_bought Minimum Tokens (token_addr) purchased. @param min_eth_bought Minimum ETH purchased as intermediary. @param deadline Time after which this transaction can no longer be executed. @param token_addr The address of the token being purchased. @return Amount of Tokens (token_addr) bought./
function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); }
5,385,836
[ 1, 2723, 13899, 261, 2316, 13, 358, 13899, 261, 2316, 67, 4793, 2934, 225, 2177, 11470, 5565, 810, 597, 5224, 876, 18, 225, 2430, 67, 87, 1673, 16811, 434, 13899, 272, 1673, 18, 225, 1131, 67, 7860, 67, 1075, 9540, 23456, 13899, 261, 2316, 67, 4793, 13, 5405, 343, 8905, 18, 225, 1131, 67, 546, 67, 1075, 9540, 23456, 512, 2455, 5405, 343, 8905, 487, 1554, 5660, 814, 18, 225, 14096, 2647, 1839, 1492, 333, 2492, 848, 1158, 7144, 506, 7120, 18, 225, 1147, 67, 4793, 1021, 1758, 434, 326, 1147, 3832, 5405, 343, 8905, 18, 327, 16811, 434, 13899, 261, 2316, 67, 4793, 13, 800, 9540, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1147, 774, 1345, 12521, 1210, 12, 203, 565, 2254, 5034, 2430, 67, 87, 1673, 16, 7010, 565, 2254, 5034, 1131, 67, 7860, 67, 1075, 9540, 16, 7010, 565, 2254, 5034, 1131, 67, 546, 67, 1075, 9540, 16, 7010, 565, 2254, 5034, 14096, 16, 7010, 565, 1758, 1147, 67, 4793, 13, 7010, 565, 1071, 1135, 261, 11890, 5034, 13, 7010, 225, 288, 203, 565, 1758, 8843, 429, 7829, 67, 4793, 273, 3272, 18, 588, 11688, 12, 2316, 67, 4793, 1769, 203, 565, 327, 1147, 774, 1345, 1210, 12, 7860, 67, 87, 1673, 16, 1131, 67, 7860, 67, 1075, 9540, 16, 1131, 67, 546, 67, 1075, 9540, 16, 14096, 16, 1234, 18, 15330, 16, 1234, 18, 15330, 16, 7829, 67, 4793, 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 ]
/* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./tools/ERC1820Client.sol"; import "./interface/ERC1820Implementer.sol"; import "./roles/MinterRole.sol"; import "./IERC1400.sol"; // Extensions import "./extensions/tokenExtensions/IERC1400TokensValidator.sol"; import "./extensions/tokenExtensions/IERC1400TokensChecker.sol"; import "./extensions/userExtensions/IERC1400TokensSender.sol"; import "./extensions/userExtensions/IERC1400TokensRecipient.sol"; /** * @title ERC1400 * @dev ERC1400 logic */ contract ERC1400 is IERC20, IERC1400, Ownable, ERC1820Client, ERC1820Implementer, MinterRole { using SafeMath for uint256; // Token string constant internal ERC1400_INTERFACE_NAME = "ERC1400Token"; string constant internal ERC20_INTERFACE_NAME = "ERC20Token"; // Token extensions string constant internal ERC1400_TOKENS_CHECKER = "ERC1400TokensChecker"; string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator"; // User extensions string constant internal ERC1400_TOKENS_SENDER = "ERC1400TokensSender"; string constant internal ERC1400_TOKENS_RECIPIENT = "ERC1400TokensRecipient"; /************************************* Token description ****************************************/ string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; bool internal _migrated; /************************************************************************************************/ /**************************************** Token behaviours **************************************/ // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Indicate whether the token can still be issued by the issuer or not anymore. bool internal _isIssuable; /************************************************************************************************/ /********************************** ERC20 Token mappings ****************************************/ // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; // Mapping from (tokenHolder, spender) to allowed value. mapping (address => mapping (address => uint256)) internal _allowed; /************************************************************************************************/ /**************************************** Documents *********************************************/ struct Doc { string docURI; bytes32 docHash; } // Mapping for token URIs. mapping(bytes32 => Doc) internal _documents; /************************************************************************************************/ /*********************************** Partitions mappings ***************************************/ // List of partitions. bytes32[] internal _totalPartitions; // Mapping from partition to their index. mapping (bytes32 => uint256) internal _indexOfTotalPartitions; // Mapping from partition to global balance of corresponding partition. mapping (bytes32 => uint256) internal _totalSupplyByPartition; // Mapping from tokenHolder to their partitions. mapping (address => bytes32[]) internal _partitionsOf; // Mapping from (tokenHolder, partition) to their index. mapping (address => mapping (bytes32 => uint256)) internal _indexOfPartitionsOf; // Mapping from (tokenHolder, partition) to balance of corresponding partition. mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition; // List of token default partitions (for ERC20 compatibility). bytes32[] internal _defaultPartitions; /************************************************************************************************/ /********************************* Global operators mappings ************************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /************************************************************************************************/ /******************************** Partition operators mappings **********************************/ // Mapping from (partition, tokenHolder, spender) to allowed value. [TOKEN-HOLDER-SPECIFIC] mapping(bytes32 => mapping (address => mapping (address => uint256))) internal _allowedByPartition; // Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC] mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition; // Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => address[]) internal _controllersByPartition; // Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition; /************************************************************************************************/ /***************************************** Modifiers ********************************************/ /** * @dev Modifier to verify if token is issuable. */ modifier isIssuableToken() { require(_isIssuable, "55"); // 0x55 funds locked (lockup period) _; } /** * @dev Modifier to make a function callable only when the contract is not migrated. */ modifier isNotMigratedToken() { require(!_migrated, "54"); // 0x54 transfers halted (contract paused) _; } /** * @dev Modifier to verifiy if sender is a minter. */ modifier onlyMinter() override { require(isMinter(msg.sender) || owner() == _msgSender()); _; } /************************************************************************************************/ /**************************** Events (additional - not mandatory) *******************************/ event ApprovalByPartition(bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value); /************************************************************************************************/ /** * @dev Initialize ERC1400 + register the contract implementation in ERC1820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param defaultPartitions Partitions chosen by default, when partition is * not specified, like the case ERC20 tranfers. */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, bytes32[] memory defaultPartitions ) public { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1); // Constructor Blocked - Token granularity can not be lower than 1 _granularity = granularity; _setControllers(controllers); _defaultPartitions = defaultPartitions; _isControllable = true; _isIssuable = true; // Register contract in ERC1820 registry ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, address(this)); ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this)); // Indicate token verifies ERC1400 and ERC20 interfaces ERC1820Implementer._setInterface(ERC1400_INTERFACE_NAME); // For migration ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); // For migration } /************************************************************************************************/ /****************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/ /************************************************************************************************/ /** * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external override view returns (uint256) { return _totalSupply; } /** * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external override view returns (uint256) { return _balances[tokenHolder]; } /** * @dev Transfer token for a specified address. * @param to The address to transfer to. * @param value The value to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) external override returns (bool) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, ""); return true; } /** * @dev Check the value 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 value of tokens still available for the spender. */ function allowance(address owner, address spender) external override view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approve(address spender, uint256 value) external override returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address which you want to transfer tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) external override returns (bool) { require( _isOperator(msg.sender, from) || (value <= _allowed[from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowed[from][msg.sender] >= value) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); } else { _allowed[from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, from, to, value, ""); return true; } /************************************************************************************************/ /****************************** EXTERNAL FUNCTIONS (ERC1400 INTERFACE) **************************/ /************************************************************************************************/ /************************************* Document Management **************************************/ /** * @dev Access a document associated with the token. * @param name Short name (represented as a bytes32) associated to the document. * @return Requested document + document hash. */ function getDocument(bytes32 name) external override view returns (string memory, bytes32) { require(bytes(_documents[name].docURI).length != 0); // Action Blocked - Empty document return ( _documents[name].docURI, _documents[name].docHash ); } /** * @dev Associate a document with the token. * @param name Short name (represented as a bytes32) associated to the document. * @param uri Document content. * @param documentHash Hash of the document [optional parameter]. */ function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external override { require(_isController[msg.sender]); _documents[name] = Doc({ docURI: uri, docHash: documentHash }); emit Document(name, uri, documentHash); } /************************************************************************************************/ /************************************** Token Information ***************************************/ /** * @dev Get balance of a tokenholder for a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which the balance is returned. * @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract. */ function balanceOfByPartition(bytes32 partition, address tokenHolder) external override view returns (uint256) { return _balanceOfByPartition[tokenHolder][partition]; } /** * @dev Get partitions index of a tokenholder. * @param tokenHolder Address for which the partitions index are returned. * @return Array of partitions index of 'tokenHolder'. */ function partitionsOf(address tokenHolder) external override view returns (bytes32[] memory) { return _partitionsOf[tokenHolder]; } /************************************************************************************************/ /****************************************** Transfers *******************************************/ /** * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. */ function transferWithData(address to, uint256 value, bytes calldata data) external override { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data); } /** * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data) external override virtual { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _transferByDefaultPartitions(msg.sender, from, to, value, data); } /************************************************************************************************/ /********************************** Partition Token Transfers ***********************************/ /** * @dev Transfer tokens from a specific partition. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. * @return Destination partition. */ function transferByPartition( bytes32 partition, address to, uint256 value, bytes calldata data ) external override returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } /** * @dev Transfer tokens from a specific partition through an operator. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. * @return Destination partition. */ function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external override returns (bytes32) { require(_isOperatorForPartition(partition, msg.sender, from) || (value <= _allowedByPartition[partition][from][msg.sender]), "53"); // 0x53 insufficient allowance if(_allowedByPartition[partition][from][msg.sender] >= value) { _allowedByPartition[partition][from][msg.sender] = _allowedByPartition[partition][from][msg.sender].sub(value); } else { _allowedByPartition[partition][from][msg.sender] = 0; } return _transferByPartition(partition, msg.sender, from, to, value, data, operatorData); } /************************************************************************************************/ /************************************* Controller Operation *************************************/ /** * @dev Know if the token can be controlled by operators. * If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future. * @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore. */ function isControllable() external override view returns (bool) { return _isControllable; } /************************************************************************************************/ /************************************* Operator Management **************************************/ /** * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external override { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external override { require(operator != msg.sender); _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * @dev Set 'operator' as an operator for 'msg.sender' for a given partition. * @param partition Name of the partition. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperatorByPartition(bytes32 partition, address operator) external override { _authorizedOperatorByPartition[msg.sender][partition][operator] = true; emit AuthorizedOperatorByPartition(partition, operator, msg.sender); } /** * @dev Remove the right of the operator address to be an operator on a given * partition for 'msg.sender' and to transfer and redeem tokens on its behalf. * @param partition Name of the partition. * @param operator Address to rescind as an operator on given partition for 'msg.sender'. */ function revokeOperatorByPartition(bytes32 partition, address operator) external override { _authorizedOperatorByPartition[msg.sender][partition][operator] = false; emit RevokedOperatorByPartition(partition, operator, msg.sender); } /************************************************************************************************/ /************************************* Operator Information *************************************/ /** * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperator(address operator, address tokenHolder) external override view returns (bool) { return _isOperator(operator, tokenHolder); } /** * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external override view returns (bool) { return _isOperatorForPartition(partition, operator, tokenHolder); } /************************************************************************************************/ /**************************************** Token Issuance ****************************************/ /** * @dev Know if new tokens can be issued in the future. * @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore. */ function isIssuable() external override view returns (bool) { return _isIssuable; } /** * @dev Issue tokens from default partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. */ function issue(address tokenHolder, uint256 value, bytes calldata data) external override onlyMinter isIssuableToken { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) _issueByPartition(_defaultPartitions[0], msg.sender, tokenHolder, value, data); } /** * @dev Issue tokens from a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. */ function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external override onlyMinter isIssuableToken { _issueByPartition(partition, msg.sender, tokenHolder, value, data); } /************************************************************************************************/ /*************************************** Token Redemption ***************************************/ /** * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. */ function redeem(uint256 value, bytes calldata data) external override { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data); } /** * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function redeemFrom(address from, uint256 value, bytes calldata data) external override virtual { require(_isOperator(msg.sender, from), "58"); // 0x58 invalid operator (transfer agent) _redeemByDefaultPartitions(msg.sender, from, value, data); } /** * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param value Number of tokens redeemed. * @param data Information attached to the redemption, by the redeemer. */ function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external override { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } /** * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to redeem tokens. * @param value Number of tokens redeemed * @param operatorData Information attached to the redemption, by the operator. */ function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata operatorData) external override { require(_isOperatorForPartition(partition, msg.sender, tokenHolder), "58"); // 0x58 invalid operator (transfer agent) _redeemByPartition(partition, msg.sender, tokenHolder, value, "", operatorData); } /************************************************************************************************/ /************************************************************************************************/ /************************ EXTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/ /************************************************************************************************/ /************************************ Token description *****************************************/ /** * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * @dev Get the number of decimals of the token. * @return The number of decimals of the token. For retrocompatibility, decimals are forced to 18 in ERC1400. */ function decimals() external pure returns(uint8) { return uint8(18); } /** * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * @dev Get list of existing partitions. * @return Array of all exisiting partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /** * @dev Get the total number of issued tokens for a given partition. * @param partition Name of the partition. * @return Total supply of tokens currently in circulation, for a given partition. */ function totalSupplyByPartition(bytes32 partition) external view returns (uint256) { return _totalSupplyByPartition[partition]; } /************************************************************************************************/ /**************************************** Token behaviours **************************************/ /** * @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders. * Once set to false, '_isControllable' can never be set to 'true' again. */ function renounceControl() external onlyOwner { _isControllable = false; } /** * @dev Definitely renounce the possibility to issue new tokens. * Once set to false, '_isIssuable' can never be set to 'true' again. */ function renounceIssuance() external onlyOwner { _isIssuable = false; } /************************************************************************************************/ /************************************ Token controllers *****************************************/ /** * @dev Get the list of controllers as defined by the token contract. * @return List of addresses of all the controllers. */ function controllers() external view returns (address[] memory) { return _controllers; } /** * @dev Get controllers for a given partition. * @param partition Name of the partition. * @return Array of controllers for partition. */ function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; } /** * @dev Set list of token controllers. * @param operators Controller addresses. */ function setControllers(address[] calldata operators) external onlyOwner { _setControllers(operators); } /** * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner { _setPartitionControllers(partition, operators); } /************************************************************************************************/ /********************************* Token default partitions *************************************/ /** * @dev Get default partitions to transfer from. * Function used for ERC20 retrocompatibility. * For example, a security token may return the bytes32("unrestricted"). * @return Array of default partitions. */ function getDefaultPartitions() external view returns (bytes32[] memory) { return _defaultPartitions; } /** * @dev Set default partitions to transfer from. * Function used for ERC20 retrocompatibility. * @param partitions partitions to use by default when not specified. */ function setDefaultPartitions(bytes32[] calldata partitions) external onlyOwner { _defaultPartitions = partitions; } /************************************************************************************************/ /******************************** Partition Token Allowances ************************************/ /** * @dev Check the value of tokens that an owner allowed to a spender. * @param partition Name of the partition. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the value of tokens still available for the spender. */ function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) { return _allowedByPartition[partition][owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of 'msg.sender'. * @param partition Name of the partition. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean that indicates if the operation was successful. */ function approveByPartition(bytes32 partition, address spender, uint256 value) external returns (bool) { require(spender != address(0), "56"); // 0x56 invalid sender _allowedByPartition[partition][msg.sender][spender] = value; emit ApprovalByPartition(partition, msg.sender, spender, value); return true; } /************************************************************************************************/ /************************************** Token extension *****************************************/ /** * @dev Set token extension contract address. * The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces. * If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed. * @param extension Address of the extension contract. * @param interfaceLabel Interface label of extension contract. * @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension. * @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter. * @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller. */ function setTokenExtension(address extension, string calldata interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) external onlyOwner { _setTokenExtension(extension, interfaceLabel, removeOldExtensionRoles, addMinterRoleForExtension, addControllerRoleForExtension); } /************************************************************************************************/ /************************************* Token migration ******************************************/ /** * @dev Migrate contract. * * ===> CAUTION: DEFINITIVE ACTION * * This function shall be called once a new version of the smart contract has been created. * Once this function is called: * - The address of the new smart contract is set in ERC1820 registry * - If the choice is definitive, the current smart contract is turned off and can never be used again * * @param newContractAddress Address of the new version of the smart contract. * @param definitive If set to 'true' the contract is turned off definitely. */ function migrate(address newContractAddress, bool definitive) external onlyOwner { _migrate(newContractAddress, definitive); } /************************************************************************************************/ /************************************************************************************************/ /************************************* INTERNAL FUNCTIONS ***************************************/ /************************************************************************************************/ /**************************************** Token Transfers ***************************************/ /** * @dev Perform the transfer of tokens. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. */ function _transferWithData( address from, address to, uint256 value ) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(to != address(0), "57"); // 0x57 invalid receiver require(_balances[from] >= value, "52"); // 0x52 insufficient balance _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); // ERC20 retrocompatibility } /** * @dev Transfer tokens from a specific partition. * @param fromPartition Partition of the tokens to transfer. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return Destination partition. */ function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length >= 64) { toPartition = _getDestinationPartition(fromPartition, data); } _callSenderExtension(fromPartition, operator, from, to, value, data, operatorData); _callTokenExtension(fromPartition, operator, from, to, value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _transferWithData(from, to, value); _addTokenToPartition(to, toPartition, value); _callRecipientExtension(toPartition, operator, from, to, value, data, operatorData); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } /** * @dev Transfer tokens from default partitions. * Function used for ERC20 retrocompatibility. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION]. */ function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data ) internal { require(_defaultPartitions.length != 0, "55"); // // 0x55 funds locked (lockup period) uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_defaultPartitions[i], operator, from, to, _remainingValue, data, ""); _remainingValue = 0; break; } else if (_localBalance != 0) { _transferByPartition(_defaultPartitions[i], operator, from, to, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "52"); // 0x52 insufficient balance } /** * @dev Retrieve the destination partition from the 'data' field. * By convention, a partition change is requested ONLY when 'data' starts * with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff * When the flag is detected, the destination tranche is extracted from the * 32 bytes following the flag. * @param fromPartition Partition of the tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @return toPartition Destination partition. */ function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } } else { toPartition = fromPartition; } } /** * @dev Remove a token from a specific partition. * @param from Token holder. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value); _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value); // If the total supply is zero, finds and deletes the partition. if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; require(index1 > 0, "50"); // 0x50 transfer failure // move the last item into the index being vacated bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index1; //_totalPartitions.length -= 1; _totalPartitions.pop(); _indexOfTotalPartitions[partition] = 0; } // If the balance of the TokenHolder's partition is zero, finds and deletes the partition. if(_balanceOfByPartition[from][partition] == 0) { uint256 index2 = _indexOfPartitionsOf[from][partition]; require(index2 > 0, "50"); // 0x50 transfer failure // move the last item into the index being vacated bytes32 lastValue = _partitionsOf[from][_partitionsOf[from].length - 1]; _partitionsOf[from][index2 - 1] = lastValue; // adjust for 1-based indexing _indexOfPartitionsOf[from][lastValue] = index2; //_partitionsOf[from].length -= 1; _partitionsOf[from].pop(); _indexOfPartitionsOf[from][partition] = 0; } } /** * @dev Add a token to a specific partition. * @param to Token recipient. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if (_indexOfPartitionsOf[to][partition] == 0) { _partitionsOf[to].push(partition); _indexOfPartitionsOf[to][partition] = _partitionsOf[to].length; } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value); if (_indexOfTotalPartitions[partition] == 0) { _totalPartitions.push(partition); _indexOfTotalPartitions[partition] = _totalPartitions.length; } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value); } } /** * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /************************************************************************************************/ /****************************************** Hooks ***********************************************/ /** * @dev Check for 'ERC1400TokensSender' user extension in ERC1820 registry and call it. * @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callSenderExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, ERC1400_TOKENS_SENDER); if (senderImplementation != address(0)) { IERC1400TokensSender(senderImplementation).tokensToTransfer(msg.data, partition, operator, from, to, value, data, operatorData); } } /** * @dev Check for 'ERC1400TokensValidator' token extension in ERC1820 registry and call it. * @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callTokenExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address validatorImplementation; validatorImplementation = interfaceAddr(address(this), ERC1400_TOKENS_VALIDATOR); if (validatorImplementation != address(0)) { IERC1400TokensValidator(validatorImplementation).tokensToValidate(msg.data, partition, operator, from, to, value, data, operatorData); } } /** * @dev Check for 'ERC1400TokensRecipient' user extension in ERC1820 registry and call it. * @param partition Name of the partition (bytes32 to be left empty for transfers where partition is not specified). * @param operator Address which triggered the balance increase (through transfer or issuance). * @param from Token holder for a transfer and 0x for an issuance. * @param to Token recipient. * @param value Number of tokens the recipient balance is increased by. * @param data Extra information, intended for the token holder ('from'). * @param operatorData Extra information attached by the operator (if any). */ function _callRecipientExtension( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal virtual { address recipientImplementation; recipientImplementation = interfaceAddr(to, ERC1400_TOKENS_RECIPIENT); if (recipientImplementation != address(0)) { IERC1400TokensRecipient(recipientImplementation).tokensReceived(msg.data, partition, operator, from, to, value, data, operatorData); } } /************************************************************************************************/ /************************************* Operator Information *************************************/ /** * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperator(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) { return (_isOperator(operator, tokenHolder) || _authorizedOperatorByPartition[tokenHolder][partition][operator] || (_isControllable && _isControllerByPartition[partition][operator]) ); } /************************************************************************************************/ /**************************************** Token Issuance ****************************************/ /** * @dev Perform the issuance of tokens. * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). */ function _issue(address operator, address to, uint256 value, bytes memory data) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(to != address(0), "57"); // 0x57 invalid receiver _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); emit Issued(operator, to, value, data); emit Transfer(address(0), to, value); // ERC20 retrocompatibility } /** * @dev Issue tokens from a specific partition. * @param toPartition Name of the partition. * @param operator The address performing the issuance. * @param to Token recipient. * @param value Number of tokens to issue. * @param data Information attached to the issuance. */ function _issueByPartition( bytes32 toPartition, address operator, address to, uint256 value, bytes memory data ) internal { _callTokenExtension(toPartition, operator, address(0), to, value, data, ""); _issue(operator, to, value, data); _addTokenToPartition(to, toPartition, value); _callRecipientExtension(toPartition, operator, address(0), to, value, data, ""); emit IssuedByPartition(toPartition, operator, to, value, data, ""); } /************************************************************************************************/ /*************************************** Token Redemption ***************************************/ /** * @dev Perform the token redemption. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function _redeem(address operator, address from, uint256 value, bytes memory data) internal isNotMigratedToken { require(_isMultiple(value), "50"); // 0x50 transfer failure require(from != address(0), "56"); // 0x56 invalid sender require(_balances[from] >= value, "52"); // 0x52 insufficient balance _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data); emit Transfer(from, address(0), value); // ERC20 retrocompatibility } /** * @dev Redeem tokens of a specific partition. * @param fromPartition Name of the partition. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByPartition( bytes32 fromPartition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { require(_balanceOfByPartition[from][fromPartition] >= value, "52"); // 0x52 insufficient balance _callSenderExtension(fromPartition, operator, from, address(0), value, data, operatorData); _callTokenExtension(fromPartition, operator, from, address(0), value, data, operatorData); _removeTokenFromPartition(from, fromPartition, value); _redeem(operator, from, value, data); emit RedeemedByPartition(fromPartition, operator, from, value, operatorData); } /** * @dev Redeem tokens from a default partitions. * @param operator The address performing the redeem. * @param from Token holder. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. */ function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data ) internal { require(_defaultPartitions.length != 0, "55"); // 0x55 funds locked (lockup period) uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _defaultPartitions.length; i++) { _localBalance = _balanceOfByPartition[from][_defaultPartitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_defaultPartitions[i], operator, from, _remainingValue, data, ""); _remainingValue = 0; break; } else { _redeemByPartition(_defaultPartitions[i], operator, from, _localBalance, data, ""); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "52"); // 0x52 insufficient balance } /************************************************************************************************/ /************************************** Transfer Validity ***************************************/ /** * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param payload Payload of the initial transaction. * @param partition Name of the partition. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function _canTransfer(bytes memory payload, bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (bytes1, bytes32, bytes32) { address checksImplementation = interfaceAddr(address(this), ERC1400_TOKENS_CHECKER); if((checksImplementation != address(0))) { return IERC1400TokensChecker(checksImplementation).canTransferByPartition(payload, partition, operator, from, to, value, data, operatorData); } else { return(hex"00", "", partition); } } /************************************************************************************************/ /************************************************************************************************/ /************************ INTERNAL FUNCTIONS (ADDITIONAL - NOT MANDATORY) ***********************/ /************************************************************************************************/ /************************************ Token controllers *****************************************/ /** * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } /** * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } /************************************************************************************************/ /************************************** Token extension *****************************************/ /** * @dev Set token extension contract address. * The extension contract can for example verify "ERC1400TokensValidator" or "ERC1400TokensChecker" interfaces. * If the extension is an "ERC1400TokensValidator", it will be called everytime a transfer is executed. * @param extension Address of the extension contract. * @param interfaceLabel Interface label of extension contract. * @param removeOldExtensionRoles If set to 'true', the roles of the old extension(minter, controller) will be removed extension. * @param addMinterRoleForExtension If set to 'true', the extension contract will be added as minter. * @param addControllerRoleForExtension If set to 'true', the extension contract will be added as controller. */ function _setTokenExtension(address extension, string memory interfaceLabel, bool removeOldExtensionRoles, bool addMinterRoleForExtension, bool addControllerRoleForExtension) internal { address oldExtension = interfaceAddr(address(this), interfaceLabel); if (oldExtension != address(0) && removeOldExtensionRoles) { if(isMinter(oldExtension)) { _removeMinter(oldExtension); } _isController[oldExtension] = false; } ERC1820Client.setInterfaceImplementation(interfaceLabel, extension); if(addMinterRoleForExtension && !isMinter(extension)) { _addMinter(extension); } if (addControllerRoleForExtension) { _isController[extension] = true; } } /************************************************************************************************/ /************************************* Token migration ******************************************/ /** * @dev Migrate contract. * * ===> CAUTION: DEFINITIVE ACTION * * This function shall be called once a new version of the smart contract has been created. * Once this function is called: * - The address of the new smart contract is set in ERC1820 registry * - If the choice is definitive, the current smart contract is turned off and can never be used again * * @param newContractAddress Address of the new version of the smart contract. * @param definitive If set to 'true' the contract is turned off definitely. */ function _migrate(address newContractAddress, bool definitive) internal { ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, newContractAddress); ERC1820Client.setInterfaceImplementation(ERC1400_INTERFACE_NAME, newContractAddress); if(definitive) { _migrated = true; } } /************************************************************************************************/ }
************************************ Operator Information *************************************/* @dev Indicate whether the operator address is an operator of the tokenHolder address. @param operator Address which may be an operator of 'tokenHolder'. @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise./
function _isOperator(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); }
7,232,142
[ 1, 5592, 15353, 342, 225, 9223, 2659, 2856, 326, 3726, 1758, 353, 392, 3726, 434, 326, 1147, 6064, 1758, 18, 225, 3726, 5267, 1492, 2026, 506, 392, 3726, 434, 296, 2316, 6064, 10332, 225, 1147, 6064, 5267, 434, 279, 1147, 10438, 1492, 2026, 1240, 326, 296, 9497, 11, 1758, 487, 392, 3726, 18, 327, 296, 3767, 11, 309, 296, 9497, 11, 353, 392, 3726, 434, 296, 2316, 6064, 11, 471, 296, 5743, 11, 3541, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 291, 5592, 12, 2867, 3726, 16, 1758, 1147, 6064, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 261, 9497, 422, 1147, 6064, 203, 1377, 747, 389, 8434, 5592, 63, 9497, 6362, 2316, 6064, 65, 203, 1377, 747, 261, 67, 291, 660, 30453, 597, 389, 291, 2933, 63, 9497, 5717, 203, 565, 11272, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/11297108109/0xc6A3397720079F3a582EBAA19a83d6Cf6E1F680C/sources/contracts/engage/Registrar.sol
wallet => nonce => bool (true if nonce has been used)
mapping(address => mapping(bytes32 => bool)) public nonces;
13,236,634
[ 1, 19177, 516, 7448, 516, 1426, 261, 3767, 309, 7448, 711, 2118, 1399, 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 ]
[ 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, 2874, 12, 2867, 516, 2874, 12, 3890, 1578, 516, 1426, 3719, 1071, 1661, 764, 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 ]
pragma solidity ^0.4.24; /** * @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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } contract SupportEscrow is Ownable { ERC20Detailed public constant bznToken = ERC20Detailed(0x1BD223e638aEb3A943b8F617335E04f3e6B6fFfa); ERC20Detailed public constant gusdToken = ERC20Detailed(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd); //BZN has 18 decimals, so we must append 18 decimals to this number uint256 public constant bznRequirement = 13213 * (10 ** uint256(18)); //gusd has two decimals, so the last two digits are for decimals //i.e 8888801 = $88,888.01 //Therefore, 330330 = $3,303.30 uint256 public constant gusdRequirement = 330330; //The minimum amount the contract must hold ($303.33) uint256 public constant gusdMinimum = 33033; //The date when assets unlock uint256 public constant unlockDate = 1551330000; bool public redeemed = false; bool public executed = false; bool public redeemable = false; address public thirdParty; modifier onlyThridParty { require(msg.sender == thirdParty); _; } constructor(address tp) public { thirdParty = tp; } function validate() public view returns (bool) { address self = address(this); uint256 bzn = bznToken.balanceOf(self); uint256 gusd = gusdToken.balanceOf(self); return bzn >= bznRequirement && gusd >= gusdRequirement; } function execute() public onlyOwner returns (bool) { //Ensure we haven't executed yet require(executed == false); address self = address(this); uint256 bzn = bznToken.balanceOf(self); //Ensure everything is in place before we execute require(bzn >= bznRequirement); //Transfer the BZN to the owner bznToken.transfer(owner(), bznRequirement); //We are done executing executed = true; } function destroy() public onlyOwner { address self = address(this); uint256 bzn = bznToken.balanceOf(self); uint256 gusd = gusdToken.balanceOf(self); //First return all funds if (executed == false) { //If it hasn't been executed yet, give funds back to third party bznToken.transfer(thirdParty, bzn); bznToken.transfer(thirdParty, gusd); } else if (redeemable && redeemed == false) { //If it hasn't been redeemed but was marked redeemable, give back to third party bznToken.transfer(thirdParty, bzn); bznToken.transfer(thirdParty, gusd); } selfdestruct(owner()); } function allowRedeem() public onlyThridParty returns (uint256) { //Ensure this has been executed require(executed); //Ensure this hasn't been marked as redeemable yet require(redeemed == false); //Ensure this hasn't been redeemed yet require(redeemable == false); //Ensure the time is past the unlock date require(block.timestamp >= unlockDate); //Ensure everything is in place before marking it as redeemable require(validate()); redeemable = true; } function redeem() public onlyOwner returns (uint256) { //Ensure this has been executed require(executed); //Ensure this is redeemable require(redeemable); //Ensure it hasn't been redeemed require(redeemed == false); //Ensure the time is past the unlock date require(block.timestamp >= unlockDate); //Ensure it's in the correct state require(validate()); //Give back the BZN to the thrid party bznToken.transfer(thirdParty, bznRequirement); //Transfer gusd to the owner gusdToken.transfer(owner(), gusdRequirement); //Mark as redeemed redeemed = true; } function withdrawBZN(uint256 amount) public onlyThridParty { //You can only do this before execute() is called //This is a safety net to ensure you don't send more than you meant to //Or to reverse this contract before execute() is called require(executed == false); //Send back BZN to the third party bznToken.transfer(thirdParty, amount); } }
First return all fundsIf it hasn't been executed yet, give funds back to third partyIf it hasn't been redeemed but was marked redeemable, give back to third party
function destroy() public onlyOwner { address self = address(this); uint256 bzn = bznToken.balanceOf(self); uint256 gusd = gusdToken.balanceOf(self); if (executed == false) { bznToken.transfer(thirdParty, bzn); bznToken.transfer(thirdParty, gusd); bznToken.transfer(thirdParty, bzn); bznToken.transfer(thirdParty, gusd); } selfdestruct(owner()); }
883,320
[ 1, 3759, 327, 777, 284, 19156, 2047, 518, 13342, 1404, 2118, 7120, 4671, 16, 8492, 284, 19156, 1473, 358, 12126, 18285, 2047, 518, 13342, 1404, 2118, 283, 24903, 329, 1496, 1703, 9350, 283, 24903, 429, 16, 8492, 1473, 358, 12126, 18285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5546, 1435, 1071, 1338, 5541, 288, 203, 3639, 1758, 365, 273, 1758, 12, 2211, 1769, 203, 540, 203, 3639, 2254, 5034, 24788, 82, 273, 24788, 82, 1345, 18, 12296, 951, 12, 2890, 1769, 203, 3639, 2254, 5034, 314, 407, 72, 273, 314, 407, 72, 1345, 18, 12296, 951, 12, 2890, 1769, 203, 540, 203, 3639, 309, 261, 4177, 4817, 422, 629, 13, 288, 203, 2398, 203, 5411, 24788, 82, 1345, 18, 13866, 12, 451, 6909, 17619, 16, 24788, 82, 1769, 203, 5411, 24788, 82, 1345, 18, 13866, 12, 451, 6909, 17619, 16, 314, 407, 72, 1769, 203, 2398, 203, 5411, 24788, 82, 1345, 18, 13866, 12, 451, 6909, 17619, 16, 24788, 82, 1769, 203, 5411, 24788, 82, 1345, 18, 13866, 12, 451, 6909, 17619, 16, 314, 407, 72, 1769, 203, 3639, 289, 203, 540, 203, 3639, 365, 5489, 8813, 12, 8443, 10663, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.4; //SPDX-License-Identifier: MIT contract CloneList { //protoId is a precursor hash to a cloneId used to identify tokenId/erc20 pairs mapping(uint256 => uint256) public protoIdToIndexHead; // mapping to track the index before a specified index // 0 <- 1 <- 2 <- 3 mapping(uint256 => mapping(uint256 => uint256)) public protoIdToIndexToPrior; // mapping to track the next index after a specified index // 0 -> 1 -> 2 -> 3 mapping(uint256 => mapping(uint256 => uint256)) public protoIdToIndexToAfter; // tracks the number of clones in circulation under a protoId mapping(uint256 => uint256) public protoIdToDepth; constructor() {} function pushListTail(uint256 protoId, uint256 index) internal { unchecked { // ethereum will be irrelevant if this ever overflows protoIdToDepth[protoId]++; // increase depth counter // index -> next protoIdToIndexToAfter[protoId][index] = index+1; // set reference **to** the next index // index <- next protoIdToIndexToPrior[protoId][index+1] = index; // set the next index's reference to previous index } } function popListIndex(uint256 protoId, uint256 index) internal { unchecked { // if clone deoesn't exist an error will throw above. should not underflow protoIdToDepth[protoId]--; // decrement clone depth counter } if (index == protoIdToIndexHead[protoId]) { // if index == indexHead move head to next index // index -> next // head = next protoIdToIndexHead[protoId] = protoIdToIndexToAfter[protoId][index]; } // index pointers will change: // prev -> index -> next // becomes: // prev ----------> next protoIdToIndexToAfter[protoId][protoIdToIndexToPrior[protoId][index]] = protoIdToIndexToAfter[protoId][index]; // prev <- index <- next // becomes: // prev <---------- next protoIdToIndexToPrior[protoId][protoIdToIndexToAfter[protoId][index]] = protoIdToIndexToPrior[protoId][index]; } function popListHead(uint256 protoId) internal { uint256 head = protoIdToIndexHead[protoId]; // indexHead -> next // head = next protoIdToIndexHead[protoId] = protoIdToIndexToAfter[protoId][head]; // move head to next index unchecked { protoIdToDepth[protoId]--; } // should not underflow, will error above if clone does not exist // index pointers will change: // prev -> index -> next // becomes: // prev ----------> next protoIdToIndexToAfter[protoId][protoIdToIndexToPrior[protoId][head]] = protoIdToIndexToAfter[protoId][head]; // prev <- index <- next // becomes: // prev <---------- next protoIdToIndexToPrior[protoId][protoIdToIndexToAfter[protoId][head]] = protoIdToIndexToPrior[protoId][head]; } function validIndex(uint256 protoId, uint256 index) internal view returns(bool) { // prev <- index // prev -> index return protoIdToIndexToAfter[protoId][protoIdToIndexToPrior[protoId][index]] == index; } }
set the next index's reference to previous index
protoIdToIndexToPrior[protoId][index+1] = index;
5,352,198
[ 1, 542, 326, 1024, 770, 1807, 2114, 358, 2416, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 3760, 548, 19418, 774, 25355, 63, 9393, 548, 6362, 1615, 15, 21, 65, 273, 770, 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/0x805712aA73aCbA8729D96683f3997Af954C47521/sources/contracts/OrangeadNFT.sol
************************************************************ From now on, these functions should be deleted when deploy to the mainnet* @dev Orangead generate free mints. No limit on amount of mints. @param _quantity Amount of tokens to mint/
function orangeadMint(uint256 _quantity) public onlyOwner { require( totalSupply() + _quantity <= maxSupply, "Not enough NFTs left to mint" ); _mint(msg.sender, _quantity); mintsPerAddress[msg.sender] += _quantity; }
12,424,276
[ 1, 1265, 2037, 603, 16, 4259, 4186, 1410, 506, 4282, 1347, 7286, 358, 326, 2774, 2758, 225, 2965, 539, 684, 2103, 4843, 312, 28142, 18, 2631, 1800, 603, 3844, 434, 312, 28142, 18, 225, 389, 16172, 16811, 434, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 578, 539, 684, 49, 474, 12, 11890, 5034, 389, 16172, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 2078, 3088, 1283, 1435, 397, 389, 16172, 1648, 943, 3088, 1283, 16, 203, 5411, 315, 1248, 7304, 423, 4464, 87, 2002, 358, 312, 474, 6, 203, 3639, 11272, 203, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 16172, 1769, 203, 3639, 312, 28142, 2173, 1887, 63, 3576, 18, 15330, 65, 1011, 389, 16172, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./IStakingRewards.sol"; import "./RewardsDistributionRecipient.sol"; import "./KeeperCompatibleInterface.sol"; contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, KeeperCompatibleInterface { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public _lockingTimeStamp; mapping(address => address) public checkUser; address[] public userList; uint256 private _actualtotalSupply; // actual total amount staked uint256 private _totalSupply; // weight total Stake amount according to tier mapping(address => uint256) private _balances; // weight Stake amount mapping(address => uint256) private _actualbalances; // actual amount staked mapping(address => uint256) private _userLockPeriod; // allow unstake after 3 months from firstStake timestamp mapping(address => uint256) private _userRewardLockPeriod; // claim reward every 3 months uint256 public lastTimeStamp; /** * Public counter variable */ uint256 public counter; uint256 public interval; /* ========== CONSTRUCTOR ========== */ constructor( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; interval = 864000; // 10 day check interval lastTimeStamp = block.timestamp; counter = 0; } /* ========== VIEWS ========== */ function userLockPeriod() external view override returns (uint256) { return _userLockPeriod[msg.sender]; } function userRewardLockPeriod() external view override returns (uint256) { return _userRewardLockPeriod[msg.sender]; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function actualTotalSupply() external view returns (uint256) { return _actualtotalSupply; } function actualBalanceOf(address account) external view returns (uint256) { return _actualbalances[account]; } function lastTimeRewardApplicable() public view override returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view override returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalSupply) ); } function earned(address account) public view override returns (uint256) { return _balances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external override nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _updateBalance(msg.sender, amount, true); stakingToken.safeTransferFrom(msg.sender, address(this), amount); // update at inital stake if (_userLockPeriod[msg.sender] < 1) { _userLockPeriod[msg.sender] = block.timestamp + 90 days; // for withdraw locking _userRewardLockPeriod[msg.sender] = block.timestamp + 90 days; // for reward locking } emit Staked(msg.sender, amount); } function stakeComponding(address uaddress) internal nonReentrant updateReward(uaddress) { uint256 rewardAmt = earned(uaddress); require(rewardAmt > 0, "Cannot stake 0"); if (earned(uaddress) > 0) { _updateBalance(uaddress, rewardAmt, true); // stakingToken.safeTransferFrom(uaddress, address(this), amount); // update at inital stake if (_userLockPeriod[uaddress] < 1) { _userLockPeriod[uaddress] = block.timestamp + 90 days; // for withdraw locking _userRewardLockPeriod[uaddress] = block.timestamp + 90 days; // for reward locking } rewards[uaddress] = 0; // setting user reward to zero since its added to stake emit RewardPaid(uaddress, rewardAmt); emit Staked(uaddress, rewardAmt); } } function stakeTransferWithBalance( uint256 amount, address useraddress, uint256 lockingPeriod ) external nonReentrant updateReward(useraddress) { require(amount > 0, "Cannot stake 0"); require(_balances[useraddress] <= 0, "Already staked by user"); _updateBalance(useraddress, amount, true); _lockingTimeStamp[useraddress] = lockingPeriod; // setting user locking ts stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(useraddress, amount); } function withdraw(uint256 amount) public override nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require( block.timestamp > _userLockPeriod[msg.sender], "Cannot withdraw before 6 month from inital stake" ); require( block.timestamp >= _lockingTimeStamp[msg.sender], "Unable to withdraw in locking period" ); _updateBalance(msg.sender, amount, false); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function _updateBalance( address userAddress, uint256 amount, bool isAdd ) internal { if (isAdd) { _actualtotalSupply = _actualtotalSupply.add(amount); _actualbalances[userAddress] = _actualbalances[userAddress].add(amount); } else { _actualtotalSupply = _actualtotalSupply.sub(amount); _actualbalances[userAddress] = _actualbalances[userAddress].sub(amount); } uint256 yield; if (_actualbalances[userAddress] >= 3000000000) { yield = 100; } else if ( _actualbalances[userAddress] >= 1500000000 && _actualbalances[userAddress] < 3000000000 ) { yield = 75; } else if ( _actualbalances[userAddress] >= 500000000 && _actualbalances[userAddress] < 1500000000 ) { yield = 63; } else if (_actualbalances[userAddress] < 500000000) { yield = 50; } uint256 newBalance = _actualbalances[userAddress].mul(yield) / 100; if (isAdd) { uint256 changedBalance = newBalance.sub(_balances[userAddress]); _totalSupply = _totalSupply.add(changedBalance); } else { uint256 changedBalance = _balances[userAddress].sub(newBalance); _totalSupply = _totalSupply.sub(changedBalance); } _balances[userAddress] = newBalance; } function getReward() public override nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; require( block.timestamp > _userRewardLockPeriod[msg.sender], "Cannot withdraw before locking reward period" ); if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); _userRewardLockPeriod[msg.sender] = block.timestamp + 10 minutes; // reward lock timestamp emit RewardPaid(msg.sender, reward); } } function enrollComponding() public nonReentrant { require(_balances[msg.sender] > 0, "Not a staker"); require( checkUser[msg.sender] != msg.sender, "Already added in compounding" ); checkUser[msg.sender] = msg.sender; userList.push(msg.sender); } function leaveComponding() public nonReentrant { require(_balances[msg.sender] > 0, "Not a staker"); require( checkUser[msg.sender] == msg.sender, "Already added in compounding" ); address[] memory tempUserList = userList; for (uint256 i = 0; i < tempUserList.length; i++) { if (tempUserList[i] == msg.sender) { tempUserList[i] = tempUserList[tempUserList.length - 1]; checkUser[msg.sender] = address(0); assembly { mstore(tempUserList, sub(mload(tempUserList), 1)) } break; } } userList = tempUserList; } function exit() external override { withdraw(_actualbalances[msg.sender]); getReward(); } function checkUpkeep(bytes calldata checkData) external view override returns (bool upkeepNeeded, bytes memory performData) { upkeepNeeded = (block.timestamp - lastTimeStamp) > interval; // We don't use the checkData in this example // checkData was defined when the Upkeep was registered performData = checkData; } function performUpkeep(bytes calldata performData) external override { require( (block.timestamp - lastTimeStamp) > interval, "Auto compound interval not reached" ); lastTimeStamp = block.timestamp; counter = counter + 1; address[] memory tempUserList = userList; uint256 currentRewardPerToken = rewardPerToken(); for (uint256 i = 0; i < tempUserList.length; i++) { address user = tempUserList[i]; if ( rewards[user] != 0 || (_balances[user] != 0 && currentRewardPerToken != userRewardPerTokenPaid[user]) ) { stakeComponding(tempUserList[i]); } } // We don't use the performData in this example // performData is generated by the Keeper's call to your `checkUpkeep` function performData; } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward, uint256 rewardsDuration) external override onlyRewardsDistribution updateReward(address(0)) { require( block.timestamp.add(rewardsDuration) >= periodFinish, "Cannot reduce existing period" ); if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward, periodFinish); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward, uint256 periodFinish); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } interface IUniswapV2ERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } contract StakingRewardsFactory is Ownable { // immutables address public rewardsToken; uint256 public stakingRewardsGenesis; // the staking tokens for which the rewards contract has been deployed address[] public stakingTokens; // info about rewards for a particular staking token struct StakingRewardsInfo { address stakingRewards; uint256 rewardAmount; uint256 duration; } // rewards info by staking token mapping(address => StakingRewardsInfo) public stakingRewardsInfoByStakingToken; constructor(address _rewardsToken, uint256 _stakingRewardsGenesis) Ownable() { require( _stakingRewardsGenesis >= block.timestamp, "StakingRewardsFactory::constructor: genesis too soon" ); rewardsToken = _rewardsToken; stakingRewardsGenesis = _stakingRewardsGenesis; } ///// permissioned functions // deploy a staking reward contract for the staking token, and store the reward amount // the reward will be distributed to the staking reward contract no sooner than the genesis function deploy( address stakingToken, uint256 rewardAmount, uint256 rewardsDuration ) public onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[ stakingToken ]; require( info.stakingRewards == address(0), "StakingRewardsFactory::deploy: already deployed" ); info.stakingRewards = address( new StakingRewards( /*_rewardsDistribution=*/ address(this), rewardsToken, stakingToken ) ); info.rewardAmount = rewardAmount; info.duration = rewardsDuration; stakingTokens.push(stakingToken); } function update( address stakingToken, uint256 rewardAmount, uint256 rewardsDuration ) public onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[ stakingToken ]; require( info.stakingRewards != address(0), "StakingRewardsFactory::update: not deployed" ); info.rewardAmount = rewardAmount; info.duration = rewardsDuration; } ///// permissionless functions // call notifyRewardAmount for all staking tokens. function notifyRewardAmounts() public { require( stakingTokens.length > 0, "StakingRewardsFactory::notifyRewardAmounts: called before any deploys" ); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } } // notify reward amount for an individual staking token. // this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts function notifyRewardAmount(address stakingToken) public { require( block.timestamp >= stakingRewardsGenesis, "StakingRewardsFactory::notifyRewardAmount: not ready" ); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[ stakingToken ]; require( info.stakingRewards != address(0), "StakingRewardsFactory::notifyRewardAmount: not deployed" ); if (info.rewardAmount > 0 && info.duration > 0) { uint256 rewardAmount = info.rewardAmount; uint256 duration = info.duration; info.rewardAmount = 0; info.duration = 0; require( IERC20(rewardsToken).transfer(info.stakingRewards, rewardAmount), "StakingRewardsFactory::notifyRewardAmount: transfer failed" ); StakingRewards(info.stakingRewards).notifyRewardAmount( rewardAmount, duration ); } } function pullExtraTokens(address token, uint256 amount) external onlyOwner { IERC20(token).transfer(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 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; /** * @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; } } // 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; abstract contract RewardsDistributionRecipient { address public rewardsDistribution; function notifyRewardAmount(uint256 reward, uint256 duration) external virtual; modifier onlyRewardsDistribution() { require( msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract" ); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface KeeperCompatibleInterface { function checkUpkeep(bytes calldata checkData) external view returns (bool upkeepNeeded, bytes memory performData); function performUpkeep(bytes calldata performData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function userLockPeriod() external view returns (uint256); function userRewardLockPeriod() external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; }
allow unstake after 3 months from firstStake timestamp
mapping(address => uint256) private _userLockPeriod;
195,674
[ 1, 5965, 640, 334, 911, 1839, 890, 8846, 628, 1122, 510, 911, 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 ]
[ 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, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 1355, 2531, 5027, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x1C7F4AA5AabC26a8255DE9427d54b210A6040fd7/sources/PolarysPort/contracts/AuctionOperator.sol
Remove the last element
sellerAuctionIds.pop();
3,817,896
[ 1, 3288, 326, 1142, 930, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 29804, 37, 4062, 2673, 18, 5120, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT-open-group pragma solidity ^0.8.0; import "ds-test/test.sol"; import "./GovernanceManager.sol"; import "./GovernanceMaxLock.sol"; import "./GovernanceProposal.sol"; import "./GovernanceStorage.sol"; import "./Governance.sol"; import "./StakeNFT.sol"; import "./interfaces/INFTStake.sol"; import "./lib/openzeppelin/token/ERC20/ERC20.sol"; import "./GovernanceProposeModifySnapshot.t.sol"; import "./facets/EthDKGLibrary.sol"; contract GovernanceProposeRestartETHDKGCopy is GovernanceProposal { // PROPOSALS MUST NOT HAVE ANY STATE VARIABLE TO AVOID POTENTIAL STORAGE // COLLISION! /// @dev function that is called when a proposal is executed. It's only /// meant to be called by the Governance Manager contract. See the /// GovernanceProposal.sol file fore more details. function execute(address self) public override returns(bool) { // Replace the following line with the address of the ETHDKG Diamond. address target = 0xEFc56627233b02eA95bAE7e19F648d7DcD5Bb132; (bool success, ) = target.call(abi.encodeWithSignature("modifyDiamondStorage(address)", self)); require(success, "GovernanceProposeModifySnapshot: CALL FAILED!"); return success; } /// @dev function that is called back by another contract with DELEGATE CALL /// rights! See the GovernanceProposal.sol file fore more details. PLACE THE /// LOGIC TO RESTART THE ETHDKG IN HERE! function callback() public override returns(bool) { EthDKGLibrary.initializeState(); return true; } } contract GovernanceProposeRestartETHDKGTest is DSTest, Setup { uint representativeNumber; function getFixtureData() internal returns ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) { admin = new AdminAccount(); AdminAccount adminMiner = new AdminAccount(); madToken = new MadTokenMock(address(this)); stakeNFT = new StakeNFT( IERC20Transfer(address(madToken)), address(admin), address(address(0x0)) ); minerStake = MinerStake(address (new StakeNFT( IERC20Transfer(address(madToken)), address(adminMiner), address(address(0x0)) ))); governanceManager = new GovernanceManager(address(stakeNFT), address(minerStake)); admin.setTokens(madToken, stakeNFT, governanceManager); adminMiner.setTokens(madToken, StakeNFT(address(minerStake)), governanceManager); } function newUserAccount(MadTokenMock madToken, StakeNFT stakeNFT, GovernanceManager governanceManager) private returns (UserAccount acct) { acct = new UserAccount(); acct.setTokens(madToken, stakeNFT, governanceManager); } function setBlockNumber(uint256 bn) internal returns (bool) { // https://github.com/dapphub/dapptools/tree/master/src/hevm#cheat-codes address externalContract = address( 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D ); (bool success, /*bytes memory returnedData*/) = externalContract.call( abi.encodeWithSignature("roll(uint256)", bn) ); return success; } function assertProposal(GovernanceStorage.Proposal memory actual, GovernanceStorage.Proposal memory expected) public { assertTrue(actual.executed == expected.executed); assertEq(actual.logic, expected.logic); assertEq(actual.voteCount, expected.voteCount); assertEq(actual.blockEndVote, expected.blockEndVote); } function testExecuteRestartETHDKG() public { ( StakeNFT stakeNFT, MinerStake minerStake, MadTokenMock madToken, AdminAccount admin, GovernanceManager governanceManager ) = getFixtureData(); sudoETHDKG.setGovernance(address(governanceManager)); GovernanceProposeRestartETHDKGCopy logic = new GovernanceProposeRestartETHDKGCopy(); emit log_named_address("Contract address", address(logic)); emit log_named_address("Snapshot address", address(ethdkg)); uint256 proposalID = governanceManager.propose(address(logic)); assertProposal( governanceManager.getProposal(proposalID), GovernanceStorage.Proposal( false, address(logic), 0, 172800 ) ); assertTrue(!governanceManager.isProposalExecuted(proposalID)); // We can only vote after 1 block has passed from the proposal creation setBlockNumber(block.number +1); for (uint256 i =0; i < 10; i++){ UserAccount user = newUserAccount(madToken, stakeNFT, governanceManager); madToken.approve(address(stakeNFT), 11_220_000 * 10**18); uint256 tokenID = stakeNFT.mintTo(address(user), 11_220_000 * 10**18, 1); user.voteAsStaker(proposalID, tokenID); } governanceManager.execute(proposalID); assertTrue(governanceManager.isProposalExecuted(proposalID)); } function testFail_ExecuteProposalRestartETHDKGWithoutPermission() public { sudoETHDKG.modifyDiamondStorage(address(this)); } }
@dev function that is called back by another contract with DELEGATE CALL rights! See the GovernanceProposal.sol file fore more details. PLACE THE LOGIC TO RESTART THE ETHDKG IN HERE!
function callback() public override returns(bool) { EthDKGLibrary.initializeState(); return true; }
990,382
[ 1, 915, 716, 353, 2566, 1473, 635, 4042, 6835, 598, 2030, 19384, 1777, 22753, 14989, 5, 2164, 326, 611, 1643, 82, 1359, 14592, 18, 18281, 585, 895, 1898, 3189, 18, 25564, 1441, 12786, 2018, 2871, 8493, 2438, 7570, 12786, 512, 2455, 3398, 43, 2120, 670, 29340, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1348, 1435, 1071, 3849, 1135, 12, 6430, 13, 288, 203, 3639, 512, 451, 3398, 43, 9313, 18, 11160, 1119, 5621, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 buidler v1.3.8 https://buidler.dev // SPDX-License-Identifier: MIT // File @openzeppelin/contracts/GSN/[email protected] 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/[email protected] 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 @animoca/ethereum-contracts-core_library/contracts/access/[email protected] pragma solidity 0.6.8; contract WhitelistedOperators is Ownable { mapping(address => bool) internal _whitelistedOperators; event WhitelistedOperator(address operator, bool enabled); /// @notice Enable or disable address operator access /// @param operator address that will be given/removed operator right. /// @param enabled set whether the operator is enabled or disabled. function whitelistOperator(address operator, bool enabled) external onlyOwner { _whitelistedOperators[operator] = enabled; emit WhitelistedOperator(operator, enabled); } /// @notice check whether address `who` is given operator rights. /// @param who The address to query. /// @return whether the address is whitelisted operator function isOperator(address who) public view returns (bool) { return _whitelistedOperators[who]; } } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File @openzeppelin/contracts/math/[email protected] 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/[email protected] 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"); } /** * @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 @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer( address indexed _from, address indexed _to, uint256 _value ); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Interface for commonly used additional ERC20 interfaces */ interface IERC20Detailed { /** * @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. * * 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); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Interface for additional ERC20 allowance features */ interface IERC20Allowance { /** * @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) external returns (bool); /** * @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) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @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}. */ abstract contract ERC20 is ERC165, Context, IERC20, IERC20Detailed, IERC20Allowance { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor() internal { _registerInterface(type(IERC20).interfaceId); _registerInterface(type(IERC20Detailed).interfaceId); _registerInterface(type(IERC20Allowance).interfaceId); // ERC20Name interfaceId: bytes4(keccak256("name()")) _registerInterface(0x06fdde03); // ERC20Symbol interfaceId: bytes4(keccak256("symbol()")) _registerInterface(0x95d89b41); // ERC20Decimals interfaceId: bytes4(keccak256("decimals()")) _registerInterface(0x313ce567); } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /** * @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; } /////////////////////////////////////////// ERC20Allowance /////////////////////////////////////// /** * @dev See {IERC20Allowance-increaseAllowance}. */ function increaseAllowance( address spender, uint256 addedValue ) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev See {IERC20Allowance-decreaseAllowance}. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// /** * @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); } /////////////////////////////////////////// Hooks /////////////////////////////////////// /** * @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. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; abstract contract ERC20WithOperators is ERC20, WhitelistedOperators { /** * NOTICE * This override will allow *any* whitelisted operator to be able to * transfer unresitricted amounts of ERC20WithOperators-based tokens from 'sender' * to 'recipient'. Care must be taken to ensure to integrity of the * whitelisted operator list. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { address msgSender = _msgSender(); // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. _msgSender()). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. if (!isOperator(msgSender)) { _approve(sender, msgSender, allowance(sender, msgSender).sub(amount)); } _transfer(sender, recipient, amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { if (isOperator(spender)) { // allow the front-end to determine whether or not an approval is // necessary, given that the whitelisted operator status of the // spender is unknown. A call to WhitelistedOperators::isOperator() // is more direct, but we want to expose a mechanism by which to // check through the ERC20 interface. return type(uint256).max; } else { return super.allowance(owner, spender); } } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.increaseAllowance(spender, addedValue); } } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.decreaseAllowance(spender, subtractedValue); } } function _approve(address owner, address spender, uint256 value) internal override { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return; } else { super._approve(owner, spender, value); } } } // File @animoca/f1dt-ethereum-contracts/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; contract REVV is ERC20WithOperators { string public override constant name = "REVV"; string public override constant symbol = "REVV"; uint8 public override constant decimals = 18; constructor ( address[] memory holders, uint256[] memory amounts ) public ERC20WithOperators() { require(holders.length == amounts.length, "REVV: wrong arguments"); for (uint256 i = 0; i < holders.length; ++i) { _mint(holders[i], amounts[i]); } } }
* @dev Interface for additional ERC20 allowance features/
interface IERC20Allowance { function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } }
2,023,249
[ 1, 1358, 364, 3312, 4232, 39, 3462, 1699, 1359, 4467, 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, 5831, 467, 654, 39, 3462, 7009, 1359, 288, 203, 203, 565, 445, 10929, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 3096, 620, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 97, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT 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"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-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.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: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interfaces/IUniswapV3CrossPoolOracle.sol"; import "./interfaces/IGStakingVault.sol"; import "./mock/Mintable.sol"; import "./interfaces/INonfungiblePositionManager.sol"; import "./interfaces/IUniswapPoolV3.sol"; import "./interfaces/IUniswapV3Factory.sol"; import "./libs/SqrtPriceMath.sol"; import "./libs/LiquidityMath.sol"; import "./libs/TickMath.sol"; contract GStakingManager is AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; uint64 private constant ACCUMULATED_MULTIPLIER = 1e12; // keccak256("BIG_GUARDIAN_ROLE") bytes32 public constant BIG_GUARDIAN_ROLE = 0x05c653944982f4fec5b037dad255d4ecd85c5b85ea2ec7654def404ae5f686ec; // keccak256("GUARDIAN_ROLE") bytes32 public constant GUARDIAN_ROLE = 0x55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041; // keccak256("MINTER_ROLE") bytes32 public constant MINTER_ROLE = 0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6; uint256 public constant USDC_THRESHOLD = 1000 * 10**6; uint256 public constant SILVER_PIVOT = 50 days; uint256 public constant GOLD_PIVOT = 100 days; uint256 public constant MAX_FAUCET = 50; uint256 public constant PERCENT = 10000; // Reward of each user. struct RewardInfo { mapping(StakeType => uint256) rewardDebt; // Reward debt. See explanation below. uint256 pendingReward; // Reward but not harvest // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (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 rewardToken; mapping(StakeType => uint256) totalReward; uint256 openTime; uint256 closeTime; mapping(StakeType => uint256) lastRewardSecond; // Last block number that rewards distribution occurs. mapping(StakeType => uint256) accRewardPerShare; // Accumulated rewards per share, times 1e12. See below. uint128 chainId; PoolType poolType; } struct StakeInfo { //for gpool uint256 amount; uint256 startStake; // start stake time // for nft uint256 nftInGpoolAmount; } struct SetTierParam { address account; Tier tier; } struct SetDateParam { address account; uint256 time; } struct LockedReward { address rewardToken; uint256 amount; } struct NFTInfo { address pool; address token0; address token1; int24 tickLower; int24 tickUpper; uint128 liquidity; uint256 amount0; uint256 amount1; } enum Tier { NORANK, BRONZE, SILVER, GOLD } enum PoolType { CLAIMABLE, REWARD_CALC } enum StakeType { GPOOL, NFT } // locking Amount if withdraw earlier mapping(uint256 => mapping(address => LockedReward)) public lockingAmounts; mapping(address => bool) public hadStake; mapping(address => StakeInfo) public stakeInfo; // Info of each pool reward mapping(uint256 => mapping(address => RewardInfo)) public rewardInfo; // Classify pools into CLAIMABLE AND REWARD_CALC mapping(PoolType => uint256[]) public poolTypes; //when you requestTokens address and blocktime+1 day is saved in Time Lock mapping(address => uint256) public lockTime; //nft record //address user => tokenId => value. mapping(address => mapping(uint256 => uint256)) public nftRecords; PoolInfo[] public poolInfo; uint256 public totalGpoolStaked; uint256 public totalNFTStaked; // calculate by gpool uint32 public twapPeriod; uint256 public gpoolRewardPercent = 5000; uint256 public firstStakingFee; //eth address payable public feeTo; // oracle state IERC20 public gpoolToken; address public weth; IERC20 public usdc; IGStakingVault public vault; IUniswapV3CrossPoolOracle public oracle; INonfungiblePositionManager public positionManager; IUniswapV3Factory public uniswapFactory; event Stake(address sender, uint256 amount, uint256 startStake); event StakeNFT(address sender, uint256 tokenId, uint256 amount, uint256 startStake); event Unstake(address sender, uint256 amount, uint256 startStake); event UnstakeNFT(address sender, uint256 tokenId, uint256 amount, uint256 startStake); event ClaimLockedReward(address sender, uint256 poolId, uint256 amount); event ClaimReward(address sender, uint256 poolId, uint256 amount); event CreatePool(uint256 poolId, PoolType poolType, uint128 chainId, address rewardToken, uint256 totalReward, uint256 openTime, uint256 closeTime); event UpdatePoolReward(uint256 poolId, uint256 amountReward); event UpdatePoolRewardRate(uint256 oldRate, uint256 newRate); event UpdatePoolTime(uint256 poolId, uint256 startTime, uint256 endTime); event SetTier(address account, Tier tier, uint256 startStake); event SetDate(address account, Tier tier, uint256 startDate); event VaultUpdated(address oldVault, address newVault); event UpdateFirstStakingFee(uint256 _fee, address payable _feeTo); /** * @notice Validate pool by pool ID * @param pid id of the pool */ modifier validatePoolById(uint256 pid) { require(pid < poolInfo.length, "StakingPool: pool is not exist"); _; } constructor( IGStakingVault _vault, IUniswapV3CrossPoolOracle _oracle, IERC20 _gpoolToken, IERC20 _usdc, address _weth, INonfungiblePositionManager _positionManager, IUniswapV3Factory _uniswapFactory, address payable _feeTo, uint256 _firstStakingFee, address[] memory _admins ) { vault = _vault; oracle = _oracle; gpoolToken = _gpoolToken; usdc = _usdc; weth = _weth; positionManager = _positionManager; uniswapFactory = _uniswapFactory; twapPeriod = 1; firstStakingFee = _firstStakingFee; feeTo = _feeTo; for (uint256 i = 0; i < _admins.length; ++i) { _setupRole(GUARDIAN_ROLE, _admins[i]); } _setRoleAdmin(GUARDIAN_ROLE, BIG_GUARDIAN_ROLE); _setupRole(GUARDIAN_ROLE, msg.sender); _setupRole(BIG_GUARDIAN_ROLE, msg.sender); } function transferBigGuardian(address _newGuardian) public onlyRole(BIG_GUARDIAN_ROLE) { require(_newGuardian != address(0) && _newGuardian != msg.sender, "Invalid new guardian"); renounceRole(BIG_GUARDIAN_ROLE, msg.sender); _setupRole(BIG_GUARDIAN_ROLE, _newGuardian); } function updateVaultAddress(address _vault) public onlyRole(BIG_GUARDIAN_ROLE) { require(_vault != address(0), "Vault address is invalid"); require(_vault != address(vault), "Vault address is exactly the same"); emit VaultUpdated(address(vault), _vault); vault = IGStakingVault(_vault); } /** * @notice allow users to call the requestTokens function to mint tokens * @param amount amount to min, in ether format */ function requestTokens(uint256 amount) external { ERC20Mintable gptoken = ERC20Mintable(address(gpoolToken)); require(amount <= MAX_FAUCET, "Can faucet max 50 token per time"); //perform a few check to make sure function can execute require(block.timestamp > lockTime[msg.sender], "lock time has not expired. Please try again later"); //set role minter _setupRole(MINTER_ROLE, msg.sender); //mint tokens gptoken.mint(msg.sender, amount); //updates locktime 1 day from now lockTime[msg.sender] = block.timestamp + 1 days; } function getTotalStake(StakeType stakeType) public view returns (uint256) { return stakeType == StakeType.GPOOL ? totalGpoolStaked : totalNFTStaked; } /** * @notice stake gpool to manager. * @param amount amount to stake */ function stake(uint256 amount) external payable nonReentrant { require(gpoolToken.balanceOf(msg.sender) >= amount, "not enough gpool"); _getStakeFeeIfNeed(msg.value, msg.sender); StakeInfo storage staker = stakeInfo[msg.sender]; require( gpoolInUSDC(staker.amount + amount + staker.nftInGpoolAmount) >= USDC_THRESHOLD, "minimum stake does not match" ); gpoolToken.safeTransferFrom(msg.sender, address(this), amount); if (staker.startStake == 0) { staker.startStake = block.timestamp; } StakeType stakeType = StakeType.GPOOL; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; if (block.timestamp <= pool.openTime) { continue; } RewardInfo storage user = rewardInfo[pid][msg.sender]; updatePool(pid, stakeType); uint256 pending = ((staker.amount * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) - user.rewardDebt[stakeType]; user.pendingReward = user.pendingReward + pending; user.rewardDebt[stakeType] = ((staker.amount + amount) * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER; } staker.amount += amount; totalGpoolStaked += amount; emit Stake(msg.sender, amount, staker.startStake); } function stakeNFT(uint256 tokenId) public payable nonReentrant { _getStakeFeeIfNeed(msg.value, msg.sender); StakeInfo storage staker = stakeInfo[msg.sender]; NFTInfo memory ntfInfo = getAmountFromTokenId(tokenId); uint256 amout0InGpool = (ntfInfo.token0 == address(gpoolToken)) ? ntfInfo.amount0 : tokenInGpool(ntfInfo.token0, ntfInfo.amount0); uint256 amout1InGpool = (ntfInfo.token1 == address(gpoolToken)) ? ntfInfo.amount1 : tokenInGpool(ntfInfo.token1, ntfInfo.amount1); uint256 amount = amout0InGpool + amout1InGpool; require( gpoolInUSDC(staker.amount + amount + staker.nftInGpoolAmount) >= USDC_THRESHOLD, "minimum stake does not match" ); positionManager.transferFrom(msg.sender, address(this), tokenId); if (staker.startStake == 0) { staker.startStake = block.timestamp; } StakeType stakeType = StakeType.NFT; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; if (block.timestamp <= pool.openTime) { continue; } RewardInfo storage user = rewardInfo[pid][msg.sender]; updatePool(pid, stakeType); uint256 pending = ((staker.nftInGpoolAmount * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) - user.rewardDebt[stakeType]; user.pendingReward = user.pendingReward + pending; user.rewardDebt[stakeType] = ((staker.nftInGpoolAmount + amount) * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER; } staker.nftInGpoolAmount += amount; totalNFTStaked += amount; nftRecords[msg.sender][tokenId] = amount; emit StakeNFT(msg.sender, tokenId, amount, staker.startStake); } /** * @notice unstake Gpool. * @param amount amount to withdraw */ function unstake(uint256 amount) external nonReentrant { StakeInfo storage staker = stakeInfo[msg.sender]; require(amount <= staker.amount, "not enough balance"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { _updateUserReward(pid, amount, StakeType.GPOOL); } staker.amount -= amount; totalGpoolStaked -= amount; if ( (staker.amount + staker.nftInGpoolAmount) == 0 || gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD ) { staker.startStake = 0; } else { staker.startStake = block.timestamp; } gpoolToken.safeTransfer(msg.sender, amount); emit Unstake(msg.sender, amount, staker.startStake); } /** * @notice unstake NFT. * @param tokenId amount to withdraw */ function unstakeNFT(uint256 tokenId) external nonReentrant { StakeInfo storage staker = stakeInfo[msg.sender]; uint256 amount = nftRecords[msg.sender][tokenId]; require(amount > 0, "invalid tokenId"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { _updateUserReward(pid, amount, StakeType.NFT); } staker.nftInGpoolAmount -= amount; totalNFTStaked -= amount; if ( (staker.amount + staker.nftInGpoolAmount) == 0 || gpoolInUSDC(staker.amount + staker.nftInGpoolAmount) < USDC_THRESHOLD ) { staker.startStake = 0; } else { staker.startStake = block.timestamp; } nftRecords[msg.sender][tokenId] = 0; positionManager.transferFrom(address(this), msg.sender, tokenId); emit UnstakeNFT(msg.sender, tokenId, amount, staker.startStake); } function _getStakeFeeIfNeed(uint256 amount, address user) private { if (!hadStake[user]) { require(amount == firstStakingFee, "Fee is not valid"); hadStake[user] = true; feeTo.transfer(amount); } else { require(amount == 0, "Fee only apply in first staking"); } } function _updateUserReward( uint256 pid, uint256 amount, StakeType stakeType ) internal { PoolInfo storage pool = poolInfo[pid]; if (block.timestamp <= pool.openTime) { return; } RewardInfo storage user = rewardInfo[pid][msg.sender]; StakeInfo storage staker = stakeInfo[msg.sender]; uint256 userAmountByType = (stakeType == StakeType.GPOOL) ? staker.amount : staker.nftInGpoolAmount; updatePool(pid, stakeType); uint256 pending = ((userAmountByType * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER) - user.rewardDebt[stakeType]; if (pending > 0) { user.pendingReward = user.pendingReward + pending; } user.rewardDebt[stakeType] = ((userAmountByType - amount) * pool.accRewardPerShare[stakeType]) / ACCUMULATED_MULTIPLIER; } function claimLockedReward(uint256 pid) public validatePoolById(pid) returns (uint256) { require(getTier(msg.sender) == Tier.GOLD, "Be gold to claim!"); LockedReward memory lockedReward = lockingAmounts[pid][msg.sender]; require(lockedReward.amount > 0, "Nothing to claim!"); vault.claimReward(address(lockedReward.rewardToken), msg.sender, lockedReward.amount); emit ClaimLockedReward(msg.sender, pid, lockedReward.amount); delete lockingAmounts[pid][msg.sender]; return lockedReward.amount; } /** * @notice Harvest proceeds msg.sender * @param pid id of the pool */ function claimReward(uint256 pid) public validatePoolById(pid) returns (uint256) { Tier userTier = getTier(msg.sender); require(getTier(msg.sender) != Tier.NORANK, "only tier"); require( gpoolInUSDC(stakeInfo[msg.sender].amount + stakeInfo[msg.sender].nftInGpoolAmount) >= USDC_THRESHOLD, "minimum stake does not match" ); PoolInfo storage pool = poolInfo[pid]; require(pool.poolType == PoolType.CLAIMABLE, "Not able to claim from reward_calc pool!"); if (block.timestamp <= pool.openTime) { return 0; } updatePool(pid, StakeType.GPOOL); updatePool(pid, StakeType.NFT); RewardInfo storage user = rewardInfo[pid][msg.sender]; StakeInfo storage staker = stakeInfo[msg.sender]; LockedReward memory lockedReward = lockingAmounts[pid][msg.sender]; uint256 totalPending = pendingReward(pid, msg.sender); user.pendingReward = 0; user.rewardDebt[StakeType.GPOOL] = (staker.amount * pool.accRewardPerShare[StakeType.GPOOL]) / (ACCUMULATED_MULTIPLIER); user.rewardDebt[StakeType.NFT] = (staker.nftInGpoolAmount * pool.accRewardPerShare[StakeType.NFT]) / (ACCUMULATED_MULTIPLIER); if (totalPending > 0) { uint256 rewardByTier = (totalPending * uint256(userTier)) / uint256(Tier.GOLD); uint256 lockedAmount = totalPending - rewardByTier; _lockUserReward(msg.sender, pid, lockedAmount); vault.claimReward(address(pool.rewardToken), msg.sender, rewardByTier); totalPending = rewardByTier; } if (userTier == Tier.GOLD && lockedReward.amount > 0) { vault.claimReward(address(pool.rewardToken), msg.sender, lockedReward.amount); emit ClaimLockedReward(msg.sender, pid, lockedReward.amount); delete lockingAmounts[pid][msg.sender]; } emit ClaimReward(msg.sender, pid, totalPending); return totalPending; } /** * @notice Harvest proceeds of all pools for msg.sender * @param pids ids of the pools */ function claimAll(uint256[] memory pids) external { uint256 length = pids.length; for (uint256 i = 0; i < length; ++i) { claimReward(pids[i]); } } /** * @notice View function to see pending rewards on frontend. * @param pid id of the pool * @param userAddress the address of the user */ function pendingReward(uint256 pid, address userAddress) public view validatePoolById(pid) returns (uint256) { PoolInfo storage pool = poolInfo[pid]; RewardInfo storage user = rewardInfo[pid][userAddress]; StakeInfo memory staker = stakeInfo[userAddress]; uint256 accRewardPerShareGpool = pool.accRewardPerShare[StakeType.GPOOL]; uint256 accRewardPerShareNFT = pool.accRewardPerShare[StakeType.NFT]; uint256 endTime = pool.closeTime < block.timestamp ? pool.closeTime : block.timestamp; // gpool if (endTime > pool.lastRewardSecond[StakeType.GPOOL] && totalGpoolStaked != 0) { uint256 poolReward = (pool.totalReward[StakeType.GPOOL] * (endTime - pool.lastRewardSecond[StakeType.GPOOL])) / (pool.closeTime - pool.openTime); accRewardPerShareGpool = (accRewardPerShareGpool + ((poolReward * ACCUMULATED_MULTIPLIER) / totalGpoolStaked)); } // nft if (endTime > pool.lastRewardSecond[StakeType.NFT] && totalNFTStaked != 0) { uint256 poolReward = (pool.totalReward[StakeType.NFT] * (endTime - pool.lastRewardSecond[StakeType.NFT])) / (pool.closeTime - pool.openTime); accRewardPerShareNFT = (accRewardPerShareNFT + ((poolReward * ACCUMULATED_MULTIPLIER) / totalNFTStaked)); } uint256 totalUserDebt = user.rewardDebt[StakeType.NFT] + user.rewardDebt[StakeType.GPOOL]; uint256 totalPendingReward = (user.pendingReward + (((staker.amount * accRewardPerShareGpool + staker.nftInGpoolAmount * accRewardPerShareNFT) / ACCUMULATED_MULTIPLIER) - totalUserDebt)); return totalPendingReward; } /** * @notice Update reward variables of the given pool to be up-to-date. * @param pid id of the pool */ function updatePool(uint256 pid, StakeType stakeType) public validatePoolById(pid) { PoolInfo storage pool = poolInfo[pid]; uint256 endTime = pool.closeTime < block.timestamp ? pool.closeTime : block.timestamp; if (endTime <= pool.lastRewardSecond[stakeType]) { return; } uint256 totalStake = getTotalStake(stakeType); if (totalStake == 0) { pool.lastRewardSecond[stakeType] = endTime; return; } uint256 poolReward = (pool.totalReward[stakeType] * (endTime - pool.lastRewardSecond[stakeType])) / (pool.closeTime - pool.openTime); uint256 deltaRewardPerShare = (poolReward * ACCUMULATED_MULTIPLIER) / totalStake; if (deltaRewardPerShare == 0 && block.timestamp < pool.closeTime) { // wait for delta > 0 return; } pool.accRewardPerShare[stakeType] = pool.accRewardPerShare[stakeType] + deltaRewardPerShare; pool.lastRewardSecond[stakeType] = endTime; } /** * @notice Update reward vairables for all pools. Be careful of gas spending! */ function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid, StakeType.GPOOL); updatePool(pid, StakeType.NFT); } } // create new pool reward function createPool( IERC20 rewardToken, uint256 totalReward, uint256 openTime, uint256 closeTime, PoolType poolType, uint128 chainId ) external onlyRole(GUARDIAN_ROLE) { require(block.timestamp <= openTime, "only future"); require(closeTime > openTime, "invalid time"); require(totalReward > 0, "invalid totalReward"); massUpdatePools(); if (poolType == PoolType.CLAIMABLE) { require(rewardToken.balanceOf(msg.sender) >= totalReward, "not enough token balance"); rewardToken.safeTransferFrom(msg.sender, address(vault), totalReward); } poolInfo.push(); PoolInfo storage pool = poolInfo[poolInfo.length - 1]; pool.rewardToken = rewardToken; pool.totalReward[StakeType.GPOOL] = (totalReward * gpoolRewardPercent) / PERCENT; pool.totalReward[StakeType.NFT] = totalReward - pool.totalReward[StakeType.GPOOL]; pool.openTime = openTime; pool.closeTime = closeTime; pool.lastRewardSecond[StakeType.GPOOL] = openTime; pool.lastRewardSecond[StakeType.NFT] = openTime; pool.poolType = poolType; pool.chainId = chainId; uint256 pid = poolInfo.length - 1; poolTypes[poolType].push(pid); emit CreatePool(pid, poolType, chainId, address(rewardToken), totalReward, openTime, closeTime); } // update startTime, endTime of pool function updatePoolTime( uint256 pid, uint256 startTime, uint256 endTime ) external onlyRole(GUARDIAN_ROLE) validatePoolById(pid) { PoolInfo storage pool = poolInfo[pid]; require(pool.openTime > block.timestamp, "pool started"); require(block.timestamp <= startTime, "only future"); require(endTime > startTime, "invalid time"); pool.openTime = startTime; pool.closeTime = endTime; pool.lastRewardSecond[StakeType.GPOOL] = startTime; pool.lastRewardSecond[StakeType.NFT] = startTime; emit UpdatePoolTime(pid, startTime, endTime); } // update total Reward of pool function updatePoolReward(uint256 pid, uint256 amountReward) external onlyRole(GUARDIAN_ROLE) validatePoolById(pid) { PoolInfo storage pool = poolInfo[pid]; require(pool.openTime > block.timestamp, "pool started"); require(amountReward > 0, "invalid totalReward"); uint256 oldTotalReward = pool.totalReward[StakeType.NFT] + pool.totalReward[StakeType.GPOOL]; pool.totalReward[StakeType.GPOOL] = (amountReward * gpoolRewardPercent) / PERCENT; pool.totalReward[StakeType.NFT] = amountReward - pool.totalReward[StakeType.GPOOL]; if (pool.poolType == PoolType.CLAIMABLE) { if (amountReward > oldTotalReward) { pool.rewardToken.safeTransferFrom(msg.sender, address(vault), amountReward - oldTotalReward); } else if (amountReward < oldTotalReward) { vault.claimReward(address(pool.rewardToken), msg.sender, oldTotalReward - amountReward); } } emit UpdatePoolReward(pid, amountReward); } function updatePoolRewardRate(uint256 _gpoolRewardPercent) public onlyRole(GUARDIAN_ROLE) { require(_gpoolRewardPercent <= PERCENT, "Rate is not valid"); uint256 oldRate = gpoolRewardPercent; gpoolRewardPercent = _gpoolRewardPercent; for (uint256 pid = 0; pid < poolInfo.length; ++pid) { PoolInfo storage pool = poolInfo[pid]; if (block.timestamp >= pool.openTime) { continue; } uint256 totalRewardByPool = pool.totalReward[StakeType.NFT] + pool.totalReward[StakeType.GPOOL]; pool.totalReward[StakeType.GPOOL] = (totalRewardByPool * gpoolRewardPercent) / PERCENT; pool.totalReward[StakeType.NFT] = totalRewardByPool - pool.totalReward[StakeType.GPOOL]; } emit UpdatePoolRewardRate(oldRate, _gpoolRewardPercent); } function updateFirstStakingFee(uint256 _fee, address payable _feeTo) public onlyRole(GUARDIAN_ROLE) { feeTo = _feeTo; firstStakingFee = _fee; emit UpdateFirstStakingFee(_fee, _feeTo); } // gpoolInUSDC // convert gpool to usdc value function gpoolInUSDC(uint256 gpoolAmount) public view returns (uint256) { // twap is in second return oracle.assetToAsset(address(gpoolToken), gpoolAmount, address(usdc), twapPeriod); } function tokenInGpool(address token, uint256 amount) public view returns (uint256) { // twap is in second return oracle.assetToAsset(address(token), amount, address(gpoolToken), twapPeriod); } // getTier: user's gpass function getTier(address user) public view returns (Tier) { StakeInfo memory staker = stakeInfo[user]; if (staker.startStake == 0) { return Tier.NORANK; } if (block.timestamp <= staker.startStake + SILVER_PIVOT) { return Tier.BRONZE; } if (block.timestamp <= staker.startStake + GOLD_PIVOT) { return Tier.SILVER; } return Tier.GOLD; } function setTwapPeriod(uint32 _twapPeriod) external onlyRole(GUARDIAN_ROLE) { twapPeriod = _twapPeriod; } function setTiers(SetTierParam[] calldata params) external onlyRole(GUARDIAN_ROLE) { uint256 length = params.length; for (uint256 i = 0; i < length; ++i) { StakeInfo storage staker = stakeInfo[params[i].account]; uint256 startStake = 0; if (params[i].tier == Tier.GOLD) { startStake = block.timestamp - GOLD_PIVOT - 1; } else if (params[i].tier == Tier.SILVER) { startStake = block.timestamp - SILVER_PIVOT - 1; } else if (params[i].tier == Tier.BRONZE) { startStake = block.timestamp - 1; } staker.startStake = startStake; emit SetTier(params[i].account, params[i].tier, startStake); } } function setDateStake(SetDateParam[] calldata params) external onlyRole(GUARDIAN_ROLE) { uint256 length = params.length; for (uint256 i = 0; i < length; ++i) { StakeInfo storage staker = stakeInfo[params[i].account]; uint256 startStake = block.timestamp - params[i].time - 1; staker.startStake = startStake; Tier tier; if (params[i].time <= 50 days) { tier = Tier.BRONZE; } else if (params[i].time <= 100 days) { tier = Tier.SILVER; } else { tier = Tier.GOLD; } emit SetDate(params[i].account, tier, startStake); } } // admin can withdraw reward token function withdrawReward(IERC20 token, uint256 amount) external onlyRole(GUARDIAN_ROLE) { require(token != gpoolToken, "only reward token"); token.safeTransfer(msg.sender, amount); } function _lockUserReward( address _user, uint256 _poolId, uint256 _lockedAmount ) internal { if (_lockedAmount > 0) { PoolInfo storage pool = poolInfo[_poolId]; LockedReward memory userLockedReward = lockingAmounts[_poolId][_user]; uint256 updatedLockingAmount = userLockedReward.amount + _lockedAmount; lockingAmounts[_poolId][_user] = LockedReward(address(pool.rewardToken), updatedLockingAmount); } } // for nft function getUniswapPoolInfo(uint256 tokenId) internal view returns (NFTInfo memory info) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = positionManager.positions(tokenId); info.pool = uniswapFactory.getPool(token0, token1, fee); info.tickLower = tickLower; info.tickUpper = tickUpper; info.liquidity = liquidity; info.token0 = token0; info.token1 = token1; } function getAmountFromTokenId(uint256 tokenId) public view returns (NFTInfo memory) { NFTInfo memory nftInfo = getUniswapPoolInfo(tokenId); require(_isValidToken(nftInfo.token0, nftInfo.token1), "NFT: Wrong NFT type"); int24 tickLower = nftInfo.tickLower; int24 tickUpper = nftInfo.tickUpper; uint128 liquidityDelta = nftInfo.liquidity; IUniswapPoolV3 uniswapPool = IUniswapPoolV3(nftInfo.pool); IUniswapPoolV3.Slot0 memory slot = uniswapPool.slot0(); uint128 liquidity = uniswapPool.liquidity(); if (slot.tick < tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it nftInfo.amount0 = SqrtPriceMath.getAmount0DeltaV2( TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidityDelta, true ); } else if (slot.tick < tickUpper) { // current tick is inside the passed range uint128 liquidityBefore = liquidity; // SLOAD for gas optimization nftInfo.amount0 = SqrtPriceMath.getAmount0DeltaV2( slot.sqrtPriceX96, TickMath.getSqrtRatioAtTick(tickUpper), liquidityDelta, true ); nftInfo.amount1 = SqrtPriceMath.getAmount1DeltaV2( TickMath.getSqrtRatioAtTick(tickLower), slot.sqrtPriceX96, liquidityDelta, true ); liquidity = LiquidityMath.addDelta(liquidityBefore, liquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it nftInfo.amount1 = SqrtPriceMath.getAmount1DeltaV2( TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidityDelta, true ); } return nftInfo; } function _isValidToken(address token0, address token1) private view returns (bool) { if ((token0 == weth && token1 == address(gpoolToken)) || (token1 == weth && token0 == address(gpoolToken))) { return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IGStakingVault { function claimReward(address _token, address _receiver, uint _amount) external; function recoverFund(address _token, address _receiver) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IERC721Permit.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol"; import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.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.8.0; interface IUniswapPoolV3 { struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the most-recently updated index of the observations array uint16 observationIndex; // the current maximum number of observations that are being stored uint16 observationCardinality; // the next maximum number of observations to store, triggered in observations.write uint16 observationCardinalityNext; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; // whether the pool is locked bool unlocked; } function slot0() external view returns (Slot0 memory); function liquidity() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; interface IUniswapV3CrossPoolOracle { function assetToAsset( address _tokenIn, uint256 _amountIn, address _tokenOut, uint32 _twapPeriod ) external view returns (uint256 amountOut); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = denominator & (~denominator + 1); // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + uint128(y)) >= x, 'LA'); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; import "./LowGasSafeMath.sol"; import "./SafeCast.sol"; import "./FullMath.sol"; import "./UnsafeMath.sol"; import "./FixedPoint96.sol"; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0DeltaV2( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1DeltaV2( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1DeltaV2(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(int256(MAX_TICK)), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } } pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title ERC20Mintable * @dev Implementation of the ERC20Mintable. Extension of {ERC20} that adds a minting behaviour. */ abstract contract ERC20Mintable is ERC20 { // indicates if minting is finished bool private _mintingFinished = false; /** * @dev Emitted during finish minting */ event MintFinished(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "ERC20Mintable: minting is finished"); _; } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @dev Function to mint tokens. * * WARNING: it allows everyone to mint new tokens. Access controls MUST be defined in derived contracts. * * @param account The address that will receive the minted tokens * @param amount The amount of tokens to mint */ function mint(address account, uint256 amount) public canMint { _mint(account, amount); } /** * @dev Function to stop minting new tokens. * * WARNING: it allows everyone to finish minting. Access controls MUST be defined in derived contracts. */ function finishMinting() public canMint { _finishMinting(); } /** * @dev Function to stop minting new tokens. */ function _finishMinting() internal virtual { _mintingFinished = true; emit MintFinished(); } }
Classify pools into CLAIMABLE AND REWARD_CALC
mapping(PoolType => uint256[]) public poolTypes;
5,408,846
[ 1, 797, 1164, 16000, 1368, 29859, 3445, 2782, 4116, 2438, 21343, 67, 7913, 39, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 2864, 559, 516, 2254, 5034, 63, 5717, 1071, 2845, 2016, 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.21; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /* Bancor Network interface */ contract IBancorNetwork { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /* Provides support and utilities for contract management Note that a managed contract must also have an owner */ contract Managed is Owned { address public manager; address public newManager; event ManagerUpdate(address indexed _prevManager, address indexed _newManager); /** @dev constructor */ function Managed() public { manager = msg.sender; } // allows execution by the manager only modifier managerOnly { assert(msg.sender == manager); _; } // allows execution by either the owner or the manager only modifier ownerOrManagerOnly { require(msg.sender == owner || msg.sender == manager); _; } /** @dev allows transferring the contract management the new manager still needs to accept the transfer can only be called by the contract manager @param _newManager new contract manager */ function transferManagement(address _newManager) public ownerOrManagerOnly { require(_newManager != manager); newManager = _newManager; } /** @dev used by a new manager to accept a management transfer */ function acceptManagement() public { require(msg.sender == newManager); emit ManagerUpdate(manager, newManager); manager = newManager; newManager = address(0); } } /** Id definitions for bancor contracts Can be used in conjunction with the contract registry to get contract addresses */ contract ContractIds { bytes32 public constant BANCOR_NETWORK = "BancorNetwork"; bytes32 public constant BANCOR_FORMULA = "BancorFormula"; bytes32 public constant CONTRACT_FEATURES = "ContractFeatures"; } /** Id definitions for bancor contract features Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() public { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* The smart token controller is an upgradable part of the smart token that allows more functionality as well as fixes for bugs/exploits. Once it accepts ownership of the token, it becomes the token's sole controller that can execute any of its functions. To upgrade the controller, ownership must be transferred to a new controller, along with any relevant data. The smart token must be set on construction and cannot be changed afterwards. Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access. Note that the controller can transfer token ownership to a new controller that doesn't allow executing any function on the token, for a trustless solution. Doing that will also remove the owner's ability to upgrade the controller. */ contract SmartTokenController is TokenHolder { ISmartToken public token; // smart token /** @dev constructor */ function SmartTokenController(ISmartToken _token) public validAddress(_token) { token = _token; } // ensures that the controller is the token's owner modifier active() { assert(token.owner() == address(this)); _; } // ensures that the controller is not the token's owner modifier inactive() { assert(token.owner() != address(this)); _; } /** @dev allows transferring the token ownership the new owner still need to accept the transfer can only be called by the contract owner @param _newOwner new token owner */ function transferTokenOwnership(address _newOwner) public ownerOnly { token.transferOwnership(_newOwner); } /** @dev used by a new owner to accept a token ownership transfer can only be called by the contract owner */ function acceptTokenOwnership() public ownerOnly { token.acceptOwnership(); } /** @dev disables/enables token transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTokenTransfers(bool _disable) public ownerOnly { token.disableTransfers(_disable); } /** @dev withdraws tokens held by the controller and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawFromToken( IERC20Token _token, address _to, uint256 _amount ) public ownerOnly { ITokenHolder(token).withdrawTokens(_token, _to, _amount); } } /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /* Bancor Converter v0.9 The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves. ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract. The converter is upgradable (just like any SmartTokenController). WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits or with very small numbers because of precision loss Open issues: - Front-running attacks are currently mitigated by the following mechanisms: - minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction - gas price limit prevents users from having control over the order of execution - gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer Other potential solutions might include a commit/reveal based schemes - Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct */ contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractIds, FeatureIds { uint32 private constant MAX_WEIGHT = 1000000; uint64 private constant MAX_CONVERSION_FEE = 1000000; struct Connector { uint256 virtualBalance; // connector virtual balance uint32 weight; // connector weight, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner bool isSet; // used to tell if the mapping element is defined } string public version = '0.9'; string public converterType = 'bancor'; IContractRegistry public registry; // contract registry contract IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public connectorTokens; // ERC20 standard token addresses IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH mapping (address => Connector) public connectors; // connector token addresses -> connector data uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100% uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, // represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%) uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee bool public conversionsEnabled = true; // true if token conversions is enabled, false if not IERC20Token[] private convertPath; // triggered when a conversion between two tokens occurs event Conversion( address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); // triggered after a conversion with new price data event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); // triggered when the conversion fee is updated event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** @dev constructor @param _token smart token governed by the converter @param _registry address of a contract registry contract @param _maxConversionFee maximum conversion fee, represented in ppm @param _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector */ function BancorConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public SmartTokenController(_token) validAddress(_registry) validMaxConversionFee(_maxConversionFee) { registry = _registry; IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); // initialize supported features if (features != address(0)) features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true); maxConversionFee = _maxConversionFee; if (_connectorToken != address(0)) addConnector(_connectorToken, _connectorWeight, false); } // validates a connector token address - verifies that the address belongs to one of the connector tokens modifier validConnector(IERC20Token _address) { require(connectors[_address].isSet); _; } // validates a token address - verifies that the address belongs to one of the convertible tokens modifier validToken(IERC20Token _address) { require(_address == token || connectors[_address].isSet); _; } // validates maximum conversion fee modifier validMaxConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE); _; } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); _; } // validates connector weight range modifier validConnectorWeight(uint32 _weight) { require(_weight > 0 && _weight <= MAX_WEIGHT); _; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } // allows execution only when conversions aren't disabled modifier conversionsAllowed { assert(conversionsEnabled); _; } // allows execution by the BancorNetwork contract only modifier bancorNetworkOnly { IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); require(msg.sender == address(bancorNetwork)); _; } /** @dev returns the number of connector tokens defined @return number of connector tokens */ function connectorTokenCount() public view returns (uint16) { return uint16(connectorTokens.length); } /* @dev allows the owner to update the registry contract address @param _registry address of a bancor converter registry contract */ function setRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @dev allows the owner to update & enable the conversion whitelist contract address when set, only addresses that are whitelisted are actually allowed to use the converter note that the whitelist check is actually done by the BancorNetwork contract @param _whitelist address of a whitelist contract */ function setConversionWhitelist(IWhitelist _whitelist) public ownerOnly notThis(_whitelist) { conversionWhitelist = _whitelist; } /* @dev allows the manager to update the quick buy path @param _path new quick buy path, see conversion path format in the bancorNetwork contract */ function setQuickBuyPath(IERC20Token[] _path) public ownerOnly validConversionPath(_path) { quickBuyPath = _path; } /* @dev allows the manager to clear the quick buy path */ function clearQuickBuyPath() public ownerOnly { quickBuyPath.length = 0; } /** @dev returns the length of the quick buy path array @return quick buy path length */ function getQuickBuyPathLength() public view returns (uint256) { return quickBuyPath.length; } /** @dev disables the entire conversion functionality this is a safety mechanism in case of a emergency can only be called by the manager @param _disable true to disable conversions, false to re-enable them */ function disableConversions(bool _disable) public ownerOrManagerOnly { conversionsEnabled = !_disable; } /** @dev updates the current conversion fee can only be called by the manager @param _conversionFee new conversion fee, represented in ppm */ function setConversionFee(uint32 _conversionFee) public ownerOrManagerOnly validConversionFee(_conversionFee) { emit ConversionFeeUpdate(conversionFee, _conversionFee); conversionFee = _conversionFee; } /* @dev given a return amount, returns the amount minus the conversion fee @param _amount return amount @param _magnitude 1 for standard conversion, 2 for cross connector conversion @return return amount minus conversion fee */ function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) { return safeMul(_amount, (MAX_CONVERSION_FEE - conversionFee) ** _magnitude) / MAX_CONVERSION_FEE ** _magnitude; } /** @dev defines a new connector for the token can only be called by the owner while the converter is inactive @param _token address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it */ function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance) public ownerOnly inactive validAddress(_token) notThis(_token) validConnectorWeight(_weight) { require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input connectors[_token].virtualBalance = 0; connectors[_token].weight = _weight; connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance; connectors[_token].isPurchaseEnabled = true; connectors[_token].isSet = true; connectorTokens.push(_token); totalConnectorWeight += _weight; } /** @dev updates one of the token connectors can only be called by the owner @param _connectorToken address of the connector token @param _weight constant connector weight, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it @param _virtualBalance new connector's virtual balance */ function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validConnector(_connectorToken) validConnectorWeight(_weight) { Connector storage connector = connectors[_connectorToken]; require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input totalConnectorWeight = totalConnectorWeight - connector.weight + _weight; connector.weight = _weight; connector.isVirtualBalanceEnabled = _enableVirtualBalance; connector.virtualBalance = _virtualBalance; } /** @dev disables purchasing with the given connector token in case the connector token got compromised can only be called by the owner note that selling is still enabled regardless of this flag and it cannot be disabled by the owner @param _connectorToken connector token contract address @param _disable true to disable the token, false to re-enable it */ function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable) public ownerOnly validConnector(_connectorToken) { connectors[_connectorToken].isPurchaseEnabled = !_disable; } /** @dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance @param _connectorToken connector token contract address @return connector balance */ function getConnectorBalance(IERC20Token _connectorToken) public view validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this); } /** @dev returns the expected return for converting a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @return expected conversion return amount */ function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return getPurchaseReturn(_fromToken, _amount); else if (_fromToken == token) return getSaleReturn(_toToken, _amount); // conversion between 2 connectors return getCrossConnectorReturn(_fromToken, _toToken, _amount); } /** @dev returns the expected return for buying the token for a connector token @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @return expected purchase return amount */ function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; require(connector.isPurchaseEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling the token for one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @return expected sale return amount */ function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount) public view active validConnector(_connectorToken) returns (uint256) { Connector storage connector = connectors[_connectorToken]; uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount); // return the amount minus the conversion fee return getFinalAmount(amount, 1); } /** @dev returns the expected return for selling one of the connector tokens for another connector token @param _fromConnectorToken contract address of the connector token to convert from @param _toConnectorToken contract address of the connector token to convert to @param _sellAmount amount to sell (in the from connector token) @return expected sale return amount (in the to connector token) */ function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount) public view active validConnector(_fromConnectorToken) validConnector(_toConnectorToken) returns (uint256) { Connector storage fromConnector = connectors[_fromConnectorToken]; Connector storage toConnector = connectors[_toConnectorToken]; require(toConnector.isPurchaseEnabled); // validate input uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken); uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken); IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA)); uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount); // return the amount minus the conversion fee // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) return getFinalAmount(amount, 2); } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public bancorNetworkOnly conversionsAllowed greaterThanZero(_minReturn) returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its connectors if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); // conversion between 2 connectors uint256 amount = getCrossConnectorReturn(_fromToken, _toToken, _amount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update the source token virtual balance if relevant Connector storage fromConnector = connectors[_fromToken]; if (fromConnector.isVirtualBalanceEnabled) fromConnector.virtualBalance = safeAdd(fromConnector.virtualBalance, _amount); // update the target token virtual balance if relevant Connector storage toConnector = connectors[_toToken]; if (toConnector.isVirtualBalanceEnabled) toConnector.virtualBalance = safeSub(toConnector.virtualBalance, amount); // ensure that the trade won't deplete the connector balance uint256 toConnectorBalance = getConnectorBalance(_toToken); assert(amount < toConnectorBalance); // transfer funds from the caller in the from connector token assert(_fromToken.transferFrom(msg.sender, this, _amount)); // transfer funds to the caller in the to connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_toToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token) uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 2)); dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount); // dispatch price data updates for the smart token / both connectors emit PriceDataUpdate(_fromToken, token.totalSupply(), getConnectorBalance(_fromToken), fromConnector.weight); emit PriceDataUpdate(_toToken, token.totalSupply(), getConnectorBalance(_toToken), toConnector.weight); return amount; } /** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */ function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { convertPath = [_fromToken, token, _toToken]; return quickConvert(convertPath, _amount, _minReturn); } /** @dev buys the token by depositing one of its connector tokens @param _connectorToken connector token contract address @param _depositAmount amount to deposit (in the connector token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return buy return amount */ function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) { uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount); // transfer funds from the caller in the connector token assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount)); // issue new funds to the caller in the smart token token.issue(msg.sender, amount); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev sells the token by withdrawing from one of its connector tokens @param _connectorToken connector token contract address @param _sellAmount amount to sell (in the smart token) @param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero @return sell return amount */ function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) { require(_sellAmount <= token.balanceOf(msg.sender)); // validate input uint256 amount = getSaleReturn(_connectorToken, _sellAmount); // ensure the trade gives something in return and meets the minimum requested amount require(amount != 0 && amount >= _minReturn); // ensure that the trade will only deplete the connector balance if the total supply is depleted as well uint256 tokenSupply = token.totalSupply(); uint256 connectorBalance = getConnectorBalance(_connectorToken); assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply)); // update virtual balance if relevant Connector storage connector = connectors[_connectorToken]; if (connector.isVirtualBalanceEnabled) connector.virtualBalance = safeSub(connector.virtualBalance, amount); // destroy _sellAmount from the caller's balance in the smart token token.destroy(msg.sender, _sellAmount); // transfer funds to the caller in the connector token // the transfer might fail if the actual connector balance is smaller than the virtual balance assert(_connectorToken.transfer(msg.sender, amount)); // calculate conversion fee and dispatch the conversion event uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1)); dispatchConversionEvent(token, _connectorToken, _sellAmount, amount, feeAmount); // dispatch price data update for the smart token/connector emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight); return amount; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the BancorNetwork contract @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable validConversionPath(_path) returns (uint256) { return quickConvertPrioritized(_path, _amount, _minReturn, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand @param _path conversion path, see conversion path format in the BancorNetwork contract @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps validating if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps validating if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps validating if the signature is legit @return tokens issued in return */ function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { IERC20Token fromToken = _path[0]; IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK)); // we need to transfer the source tokens from the caller to the BancorNetwork contract, // so it can execute the conversion on behalf of the caller if (msg.value == 0) { // not ETH, send the source tokens to the BancorNetwork contract // if the token is the smart token, no allowance is required - destroy the tokens // from the caller and issue them to the BancorNetwork contract if (fromToken == token) { token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract } else { // otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract assert(fromToken.transferFrom(msg.sender, bancorNetwork, _amount)); } } // execute the conversion and pass on the ETH with the call return bancorNetwork.convertForPrioritized.value(msg.value)(_path, _amount, _minReturn, msg.sender, _block, _v, _r, _s); } // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { return convertInternal(_fromToken, _toToken, _amount, _minReturn); } /** @dev helper, dispatches the Conversion event @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount purchased/sold (in the source token) @param _returnAmount amount returned (in the target token) */ function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private { // fee amount is converted to 255 bits - // negative amount means the fee is taken from the source token, positive amount means its taken from the target token // currently the fee is always taken from the target token // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow assert(_feeAmount <= 2 ** 255); emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount)); } /** @dev fallback, buys the smart token with ETH note that the purchase will use the price at the time of the purchase */ function() payable public { quickConvert(quickBuyPath, msg.value, 1); } } /* Bancor Converter Factory interface */ contract IBancorConverterFactory { function createConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public returns (address); } /* Bancor Converter Factory */ contract BancorConverterFactory is IBancorConverterFactory { // triggered when a new converter is created event NewConverter(address indexed _converter, address indexed _owner); /** @dev constructor */ function BancorConverterFactory() public { } /** @dev creates a new converter with the given arguments and transfers the ownership and management to the sender. @param _token smart token governed by the converter @param _registry address of a contract registry contract @param _maxConversionFee maximum conversion fee, represented in ppm @param _connectorToken optional, initial connector, allows defining the first connector at deployment time @param _connectorWeight optional, weight for the initial connector @return a new converter */ function createConverter( ISmartToken _token, IContractRegistry _registry, uint32 _maxConversionFee, IERC20Token _connectorToken, uint32 _connectorWeight ) public returns(address converterAddress) { BancorConverter converter = new BancorConverter( _token, _registry, _maxConversionFee, _connectorToken, _connectorWeight ); converter.transferOwnership(msg.sender); converter.transferManagement(msg.sender); address _converterAddress = address(converter); emit NewConverter(_converterAddress, msg.sender); return _converterAddress; } }
validates conversion fee
modifier validConversionFee(uint32 _conversionFee) { require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); _; }
14,572
[ 1, 877, 815, 4105, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 923, 6814, 14667, 12, 11890, 1578, 389, 20990, 14667, 13, 288, 203, 3639, 2583, 24899, 20990, 14667, 1545, 374, 597, 389, 20990, 14667, 1648, 943, 6814, 14667, 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 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (governance/utils/IVotes.sol) pragma solidity ^0.8.0; /** * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. * * _Available since v4.5._ */ interface IVotes { /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) external view returns (uint256); /** * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). */ function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. */ function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) external view returns (address); /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) external; /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (governance/utils/Votes.sol) pragma solidity ^0.8.0; import "../../utils/Context.sol"; import "../../utils/Counters.sol"; import "../../utils/Checkpoints.sol"; import "../../utils/cryptography/draft-EIP712.sol"; import "./IVotes.sol"; /** * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of * "representative" that will pool delegated voting units from different accounts and can then use it to vote in * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative. * * This contract is often combined with a token contract such that voting units correspond to token units. For an * example, see {ERC721Votes}. * * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the * cost of this history tracking optional. * * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the * previous example, it would be included in {ERC721-_beforeTokenTransfer}). * * _Available since v4.5._ */ abstract contract Votes is IVotes, Context, EIP712 { using Checkpoints for Checkpoints.History; using Counters for Counters.Counter; bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegation; mapping(address => Checkpoints.History) private _delegateCheckpoints; Checkpoints.History private _totalCheckpoints; mapping(address => Counters.Counter) private _nonces; /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) public view virtual override returns (uint256) { return _delegateCheckpoints[account].latest(); } /** * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { return _delegateCheckpoints[account].getAtBlock(blockNumber); } /** * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < block.number, "Votes: block not yet mined"); return _totalCheckpoints.getAtBlock(blockNumber); } /** * @dev Returns the current total supply of votes. */ function _getTotalSupply() internal view virtual returns (uint256) { return _totalCheckpoints.latest(); } /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) public view virtual override returns (address) { return _delegation[account]; } /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual override { address account = _msgSender(); _delegate(account, delegatee); } /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Delegate all of `account`'s voting units to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address account, address delegatee) internal virtual { address oldDelegate = delegates(account); _delegation[account] = delegatee; emit DelegateChanged(account, oldDelegate, delegatee); _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); } /** * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` * should be zero. Total supply of voting units will be adjusted with mints and burns. */ function _transferVotingUnits( address from, address to, uint256 amount ) internal virtual { if (from == address(0)) { _totalCheckpoints.push(_add, amount); } if (to == address(0)) { _totalCheckpoints.push(_subtract, amount); } _moveDelegateVotes(delegates(from), delegates(to), amount); } /** * @dev Moves delegated votes from one delegate to another. */ function _moveDelegateVotes( address from, address to, uint256 amount ) private { if (from != to && amount > 0) { if (from != address(0)) { (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[from].push(_subtract, amount); emit DelegateVotesChanged(from, oldValue, newValue); } if (to != address(0)) { (uint256 oldValue, uint256 newValue) = _delegateCheckpoints[to].push(_add, amount); emit DelegateVotesChanged(to, oldValue, newValue); } } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } /** * @dev Consumes a nonce. * * Returns the current value and increments nonce. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } /** * @dev Returns an address nonce. */ function nonces(address owner) public view virtual returns (uint256) { return _nonces[owner].current(); } /** * @dev Returns the contract's {EIP712} domain separator. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparatorV4(); } /** * @dev Must return the voting units held by an account. */ function _getVotingUnits(address) internal virtual returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/extensions/draft-ERC721Votes.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../governance/utils/Votes.sol"; /** * @dev Extension of ERC721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts * as 1 vote unit. * * Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost * on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of * the votes in governance decisions, or they can delegate to themselves to be their own representative. * * _Available since v4.5._ */ abstract contract ERC721Votes is ERC721, Votes { /** * @dev Adjusts votes when tokens are transferred. * * Emits a {Votes-DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { _transferVotingUnits(from, to, 1); super._afterTokenTransfer(from, to, tokenId); } /** * @dev Returns the balance of `account`. */ function _getVotingUnits(address account) internal virtual override returns (uint256) { return balanceOf(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Checkpoints.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; import "./math/SafeCast.sol"; /** * @dev This library defines the `History` struct, for checkpointing values as they change at different points in * time, and later looking up past values by block number. See {Votes} as an example. * * To create a history of checkpoints define a variable type `Checkpoints.History` in your contract, and store a new * checkpoint for the current transaction block using the {push} function. * * _Available since v4.5._ */ library Checkpoints { struct Checkpoint { uint32 _blockNumber; uint224 _value; } struct History { Checkpoint[] _checkpoints; } /** * @dev Returns the value in the latest checkpoint, or zero if there are no checkpoints. */ function latest(History storage self) internal view returns (uint256) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : self._checkpoints[pos - 1]._value; } /** * @dev Returns the value at a given block number. If a checkpoint is not available at that block, the closest one * before it is returned, or zero otherwise. */ function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256) { require(blockNumber < block.number, "Checkpoints: block not yet mined"); uint256 high = self._checkpoints.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (self._checkpoints[mid]._blockNumber > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : self._checkpoints[high - 1]._value; } /** * @dev Pushes a value onto a History so that it is stored as the checkpoint for the current block. * * Returns previous value and new value. */ function push(History storage self, uint256 value) internal returns (uint256, uint256) { uint256 pos = self._checkpoints.length; uint256 old = latest(self); if (pos > 0 && self._checkpoints[pos - 1]._blockNumber == block.number) { self._checkpoints[pos - 1]._value = SafeCast.toUint224(value); } else { self._checkpoints.push( Checkpoint({_blockNumber: SafeCast.toUint32(block.number), _value: SafeCast.toUint224(value)}) ); } return (old, value); } /** * @dev Pushes a value onto a History, by updating the latest value using binary operation `op`. The new value will * be set to `op(latest, delta)`. * * Returns previous value and new value. */ function push( History storage self, function(uint256, uint256) view returns (uint256) op, uint256 delta ) internal returns (uint256, uint256) { return push(self, op(latest(self), delta)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/draft-ERC721Votes.sol'; import './abstract/JBOperatable.sol'; import './interfaces/IJBProjects.sol'; import './libraries/JBOperations.sol'; /** @notice Stores project ownership and metadata. @dev Projects are represented as ERC-721's. @dev Adheres to: IJBProjects: General interface for the methods in this contract that interact with the blockchain's state according to the protocol's rules. @dev Inherits from: JBOperatable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions. ERC721Votes: A checkpointable standard definition for non-fungible tokens (NFTs). Ownable: Includes convenience functionality for checking a message sender's permissions before executing certain transactions. */ contract JBProjects is IJBProjects, JBOperatable, ERC721Votes, Ownable { //*********************************************************************// // --------------------- public stored properties -------------------- // //*********************************************************************// /** @notice The number of projects that have been created using this contract. @dev The count is incremented with each new project created. The resulting ERC-721 token ID for each project is the newly incremented count value. */ uint256 public override count = 0; /** @notice The metadata for each project, which can be used across several domains. _projectId The ID of the project to which the metadata belongs. _domain The domain within which the metadata applies. Applications can use the domain namespace as they wish. */ mapping(uint256 => mapping(uint256 => string)) public override metadataContentOf; /** @notice The contract resolving each project ID to its ERC721 URI. */ IJBTokenUriResolver public override tokenUriResolver; //*********************************************************************// // ------------------------- external views -------------------------- // //*********************************************************************// /** @notice Returns the URI where the ERC-721 standard JSON of a project is hosted. @param _projectId The ID of the project to get a URI of. @return The token URI to use for the provided `_projectId`. */ function tokenURI(uint256 _projectId) public view override returns (string memory) { // If there's no resolver, there's no URI. if (tokenUriResolver == IJBTokenUriResolver(address(0))) return ''; // Return the resolved URI. return tokenUriResolver.getUri(_projectId); } //*********************************************************************// // -------------------------- constructor ---------------------------- // //*********************************************************************// /** @param _operatorStore A contract storing operator assignments. */ constructor(IJBOperatorStore _operatorStore) ERC721('Juicebox Projects', 'JUICEBOX') EIP712('Juicebox Projects', '1') JBOperatable(_operatorStore) // solhint-disable-next-line no-empty-blocks { } //*********************************************************************// // ---------------------- external transactions ---------------------- // //*********************************************************************// /** @notice Create a new project for the specified owner, which mints an NFT (ERC-721) into their wallet. @dev Anyone can create a project on an owner's behalf. @param _owner The address that will be the owner of the project. @param _metadata A struct containing metadata content about the project, and domain within which the metadata applies. @return projectId The token ID of the newly created project. */ function createFor(address _owner, JBProjectMetadata calldata _metadata) external override returns (uint256 projectId) { // Increment the count, which will be used as the ID. projectId = ++count; // Mint the project. _safeMint(_owner, projectId); // Set the metadata if one was provided. if (bytes(_metadata.content).length > 0) metadataContentOf[projectId][_metadata.domain] = _metadata.content; emit Create(projectId, _owner, _metadata, msg.sender); } /** @notice Allows a project owner to set the project's metadata content for a particular domain namespace. @dev Only a project's owner or operator can set its metadata. @dev Applications can use the domain namespace as they wish. @param _projectId The ID of the project who's metadata is being changed. @param _metadata A struct containing metadata content, and domain within which the metadata applies. */ function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata) external override requirePermission(ownerOf(_projectId), _projectId, JBOperations.SET_METADATA) { // Set the project's new metadata content within the specified domain. metadataContentOf[_projectId][_metadata.domain] = _metadata.content; emit SetMetadata(_projectId, _metadata, msg.sender); } /** @notice Sets the address of the resolver used to retrieve the tokenURI of projects. @param _newResolver The address of the new resolver. */ function setTokenUriResolver(IJBTokenUriResolver _newResolver) external override onlyOwner { // Store the new resolver. tokenUriResolver = _newResolver; emit SetTokenUriResolver(_newResolver, msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBOperatable.sol'; //*********************************************************************// // --------------------------- custom errors -------------------------- // //*********************************************************************// error UNAUTHORIZED(); /** @notice Modifiers to allow access to functions based on the message sender's operator status. */ abstract contract JBOperatable is IJBOperatable { //*********************************************************************// // ---------------------------- modifiers ---------------------------- // //*********************************************************************// modifier requirePermission( address _account, uint256 _domain, uint256 _permissionIndex ) { _requirePermission(_account, _domain, _permissionIndex); _; } modifier requirePermissionAllowingOverride( address _account, uint256 _domain, uint256 _permissionIndex, bool _override ) { _requirePermissionAllowingOverride(_account, _domain, _permissionIndex, _override); _; } //*********************************************************************// // ---------------- public immutable stored properties --------------- // //*********************************************************************// /** @notice A contract storing operator assignments. */ IJBOperatorStore public immutable override operatorStore; //*********************************************************************// // -------------------------- constructor ---------------------------- // //*********************************************************************// /** @param _operatorStore A contract storing operator assignments. */ constructor(IJBOperatorStore _operatorStore) { operatorStore = _operatorStore; } //*********************************************************************// // -------------------------- internal views ------------------------- // //*********************************************************************// /** @notice Require the message sender is either the account or has the specified permission. @param _account The account to allow. @param _domain The domain within which the permission index will be checked. @param _domain The permission index that an operator must have within the specified domain to be allowed. */ function _requirePermission( address _account, uint256 _domain, uint256 _permissionIndex ) internal view { if ( msg.sender != _account && !operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) && !operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex) ) revert UNAUTHORIZED(); } /** @notice Require the message sender is either the account, has the specified permission, or the override condition is true. @param _account The account to allow. @param _domain The domain within which the permission index will be checked. @param _domain The permission index that an operator must have within the specified domain to be allowed. @param _override The override condition to allow. */ function _requirePermissionAllowingOverride( address _account, uint256 _domain, uint256 _permissionIndex, bool _override ) internal view { if ( !_override && msg.sender != _account && !operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) && !operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex) ) revert UNAUTHORIZED(); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; enum JBBallotState { Active, Approved, Failed } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../structs/JBFundingCycleData.sol'; import './../structs/JBFundingCycleMetadata.sol'; import './../structs/JBProjectMetadata.sol'; import './../structs/JBGroupedSplits.sol'; import './../structs/JBFundAccessConstraints.sol'; import './../structs/JBProjectMetadata.sol'; import './IJBDirectory.sol'; import './IJBToken.sol'; import './IJBPaymentTerminal.sol'; import './IJBFundingCycleStore.sol'; import './IJBTokenStore.sol'; import './IJBSplitsStore.sol'; interface IJBController { event LaunchProject(uint256 configuration, uint256 projectId, string memo, address caller); event LaunchFundingCycles(uint256 configuration, uint256 projectId, string memo, address caller); event ReconfigureFundingCycles( uint256 configuration, uint256 projectId, string memo, address caller ); event SetFundAccessConstraints( uint256 indexed fundingCycleConfiguration, uint256 indexed fundingCycleNumber, uint256 indexed projectId, JBFundAccessConstraints constraints, address caller ); event DistributeReservedTokens( uint256 indexed fundingCycleConfiguration, uint256 indexed fundingCycleNumber, uint256 indexed projectId, address beneficiary, uint256 tokenCount, uint256 beneficiaryTokenCount, string memo, address caller ); event DistributeToReservedTokenSplit( uint256 indexed projectId, uint256 indexed domain, uint256 indexed group, JBSplit split, uint256 tokenCount, address caller ); event MintTokens( address indexed beneficiary, uint256 indexed projectId, uint256 tokenCount, uint256 beneficiaryTokenCount, string memo, uint256 reservedRate, address caller ); event BurnTokens( address indexed holder, uint256 indexed projectId, uint256 tokenCount, string memo, address caller ); event Migrate(uint256 indexed projectId, IJBController to, address caller); event PrepMigration(uint256 indexed projectId, IJBController from, address caller); function projects() external view returns (IJBProjects); function fundingCycleStore() external view returns (IJBFundingCycleStore); function tokenStore() external view returns (IJBTokenStore); function splitsStore() external view returns (IJBSplitsStore); function directory() external view returns (IJBDirectory); function reservedTokenBalanceOf(uint256 _projectId, uint256 _reservedRate) external view returns (uint256); function distributionLimitOf( uint256 _projectId, uint256 _configuration, IJBPaymentTerminal _terminal, address _token ) external view returns (uint256 distributionLimit, uint256 distributionLimitCurrency); function overflowAllowanceOf( uint256 _projectId, uint256 _configuration, IJBPaymentTerminal _terminal, address _token ) external view returns (uint256 overflowAllowance, uint256 overflowAllowanceCurrency); function totalOutstandingTokensOf(uint256 _projectId, uint256 _reservedRate) external view returns (uint256); function currentFundingCycleOf(uint256 _projectId) external returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata); function queuedFundingCycleOf(uint256 _projectId) external returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata); function launchProjectFor( address _owner, JBProjectMetadata calldata _projectMetadata, JBFundingCycleData calldata _data, JBFundingCycleMetadata calldata _metadata, uint256 _mustStartAtOrAfter, JBGroupedSplits[] memory _groupedSplits, JBFundAccessConstraints[] memory _fundAccessConstraints, IJBPaymentTerminal[] memory _terminals, string calldata _memo ) external returns (uint256 projectId); function launchFundingCyclesFor( uint256 _projectId, JBFundingCycleData calldata _data, JBFundingCycleMetadata calldata _metadata, uint256 _mustStartAtOrAfter, JBGroupedSplits[] memory _groupedSplits, JBFundAccessConstraints[] memory _fundAccessConstraints, IJBPaymentTerminal[] memory _terminals, string calldata _memo ) external returns (uint256 configuration); function reconfigureFundingCyclesOf( uint256 _projectId, JBFundingCycleData calldata _data, JBFundingCycleMetadata calldata _metadata, uint256 _mustStartAtOrAfter, JBGroupedSplits[] memory _groupedSplits, JBFundAccessConstraints[] memory _fundAccessConstraints, string calldata _memo ) external returns (uint256); function issueTokenFor( uint256 _projectId, string calldata _name, string calldata _symbol ) external returns (IJBToken token); function changeTokenOf( uint256 _projectId, IJBToken _token, address _newOwner ) external; function mintTokensOf( uint256 _projectId, uint256 _tokenCount, address _beneficiary, string calldata _memo, bool _preferClaimedTokens, bool _useReservedRate ) external returns (uint256 beneficiaryTokenCount); function burnTokensOf( address _holder, uint256 _projectId, uint256 _tokenCount, string calldata _memo, bool _preferClaimedTokens ) external; function distributeReservedTokensOf(uint256 _projectId, string memory _memo) external returns (uint256); function prepForMigrationOf(uint256 _projectId, IJBController _from) external; function migrate(uint256 _projectId, IJBController _to) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBPaymentTerminal.sol'; import './IJBProjects.sol'; import './IJBFundingCycleStore.sol'; import './IJBController.sol'; interface IJBDirectory { event SetController(uint256 indexed projectId, IJBController indexed controller, address caller); event AddTerminal(uint256 indexed projectId, IJBPaymentTerminal indexed terminal, address caller); event SetTerminals(uint256 indexed projectId, IJBPaymentTerminal[] terminals, address caller); event SetPrimaryTerminal( uint256 indexed projectId, address indexed token, IJBPaymentTerminal indexed terminal, address caller ); event SetIsAllowedToSetFirstController(address indexed addr, bool indexed flag, address caller); function projects() external view returns (IJBProjects); function fundingCycleStore() external view returns (IJBFundingCycleStore); function controllerOf(uint256 _projectId) external view returns (IJBController); function isAllowedToSetFirstController(address _address) external view returns (bool); function terminalsOf(uint256 _projectId) external view returns (IJBPaymentTerminal[] memory); function isTerminalOf(uint256 _projectId, IJBPaymentTerminal _terminal) external view returns (bool); function primaryTerminalOf(uint256 _projectId, address _token) external view returns (IJBPaymentTerminal); function setControllerOf(uint256 _projectId, IJBController _controller) external; function setTerminalsOf(uint256 _projectId, IJBPaymentTerminal[] calldata _terminals) external; function setPrimaryTerminalOf( uint256 _projectId, address _token, IJBPaymentTerminal _terminal ) external; function setIsAllowedToSetFirstController(address _address, bool _flag) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBFundingCycleStore.sol'; import './../enums/JBBallotState.sol'; interface IJBFundingCycleBallot { function duration() external view returns (uint256); function stateOf( uint256 _projectId, uint256 _configuration, uint256 _start ) external view returns (JBBallotState); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBFundingCycleStore.sol'; import './IJBPayDelegate.sol'; import './IJBRedemptionDelegate.sol'; import './../structs/JBPayParamsData.sol'; import './../structs/JBRedeemParamsData.sol'; interface IJBFundingCycleDataSource { function payParams(JBPayParamsData calldata _data) external view returns ( uint256 weight, string memory memo, IJBPayDelegate delegate ); function redeemParams(JBRedeemParamsData calldata _data) external view returns ( uint256 reclaimAmount, string memory memo, IJBRedemptionDelegate delegate ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBFundingCycleBallot.sol'; import './../enums/JBBallotState.sol'; import './../structs/JBFundingCycle.sol'; import './../structs/JBFundingCycleData.sol'; interface IJBFundingCycleStore { event Configure( uint256 indexed configuration, uint256 indexed projectId, JBFundingCycleData data, uint256 metadata, uint256 mustStartAtOrAfter, address caller ); event Init(uint256 indexed configuration, uint256 indexed projectId, uint256 indexed basedOn); function latestConfigurationOf(uint256 _projectId) external view returns (uint256); function get(uint256 _projectId, uint256 _configuration) external view returns (JBFundingCycle memory); function queuedOf(uint256 _projectId) external view returns (JBFundingCycle memory); function currentOf(uint256 _projectId) external view returns (JBFundingCycle memory); function currentBallotStateOf(uint256 _projectId) external view returns (JBBallotState); function configureFor( uint256 _projectId, JBFundingCycleData calldata _data, uint256 _metadata, uint256 _mustStartAtOrAfter ) external returns (JBFundingCycle memory fundingCycle); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBOperatorStore.sol'; interface IJBOperatable { function operatorStore() external view returns (IJBOperatorStore); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../structs/JBOperatorData.sol'; interface IJBOperatorStore { event SetOperator( address indexed operator, address indexed account, uint256 indexed domain, uint256[] permissionIndexes, uint256 packed ); function permissionsOf( address _operator, address _account, uint256 _domain ) external view returns (uint256); function hasPermission( address _operator, address _account, uint256 _domain, uint256 _permissionIndex ) external view returns (bool); function hasPermissions( address _operator, address _account, uint256 _domain, uint256[] calldata _permissionIndexes ) external view returns (bool); function setOperator(JBOperatorData calldata _operatorData) external; function setOperators(JBOperatorData[] calldata _operatorData) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../structs/JBDidPayData.sol'; interface IJBPayDelegate { function didPay(JBDidPayData calldata _data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBDirectory.sol'; interface IJBPaymentTerminal { function acceptsToken(address _token) external view returns (bool); function currencyForToken(address _token) external view returns (uint256); function decimalsForToken(address _token) external view returns (uint256); // Return value must be a fixed point number with 18 decimals. function currentEthOverflowOf(uint256 _projectId) external view returns (uint256); function pay( uint256 _projectId, uint256 _amount, address _token, address _beneficiary, uint256 _minReturnedTokens, bool _preferClaimedTokens, string calldata _memo, bytes calldata _metadata ) external payable returns (uint256 beneficiaryTokenCount); function addToBalanceOf( uint256 _projectId, uint256 _amount, address _token, string calldata _memo ) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import './IJBPaymentTerminal.sol'; import './IJBTokenUriResolver.sol'; import './../structs/JBProjectMetadata.sol'; import './IJBTokenUriResolver.sol'; interface IJBProjects is IERC721 { event Create( uint256 indexed projectId, address indexed owner, JBProjectMetadata metadata, address caller ); event SetMetadata(uint256 indexed projectId, JBProjectMetadata metadata, address caller); event SetTokenUriResolver(IJBTokenUriResolver resolver, address caller); function count() external view returns (uint256); function metadataContentOf(uint256 _projectId, uint256 _domain) external view returns (string memory); function tokenUriResolver() external view returns (IJBTokenUriResolver); function createFor(address _owner, JBProjectMetadata calldata _metadata) external returns (uint256 projectId); function setMetadataOf(uint256 _projectId, JBProjectMetadata calldata _metadata) external; function setTokenUriResolver(IJBTokenUriResolver _newResolver) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBFundingCycleStore.sol'; import './../structs/JBDidRedeemData.sol'; interface IJBRedemptionDelegate { function didRedeem(JBDidRedeemData calldata _data) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import '../structs/JBSplitAllocationData.sol'; interface IJBSplitAllocator { function allocate(JBSplitAllocationData calldata _data) external payable; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBOperatorStore.sol'; import './IJBProjects.sol'; import './IJBDirectory.sol'; import './IJBSplitAllocator.sol'; import './../structs/JBSplit.sol'; interface IJBSplitsStore { event SetSplit( uint256 indexed projectId, uint256 indexed domain, uint256 indexed group, JBSplit split, address caller ); function projects() external view returns (IJBProjects); function directory() external view returns (IJBDirectory); function splitsOf( uint256 _projectId, uint256 _domain, uint256 _group ) external view returns (JBSplit[] memory); function set( uint256 _projectId, uint256 _domain, uint256 _group, JBSplit[] memory _splits ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IJBToken { function decimals() external view returns (uint8); function totalSupply(uint256 _projectId) external view returns (uint256); function balanceOf(address _account, uint256 _projectId) external view returns (uint256); function mint( uint256 _projectId, address _account, uint256 _amount ) external; function burn( uint256 _projectId, address _account, uint256 _amount ) external; function approve( uint256, address _spender, uint256 _amount ) external; function transfer( uint256 _projectId, address _to, uint256 _amount ) external; function transferFrom( uint256 _projectId, address _from, address _to, uint256 _amount ) external; function transferOwnership(address _newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './IJBProjects.sol'; import './IJBToken.sol'; interface IJBTokenStore { event Issue( uint256 indexed projectId, IJBToken indexed token, string name, string symbol, address caller ); event Mint( address indexed holder, uint256 indexed projectId, uint256 amount, bool tokensWereClaimed, bool preferClaimedTokens, address caller ); event Burn( address indexed holder, uint256 indexed projectId, uint256 amount, uint256 initialUnclaimedBalance, uint256 initialClaimedBalance, bool preferClaimedTokens, address caller ); event Claim( address indexed holder, uint256 indexed projectId, uint256 initialUnclaimedBalance, uint256 amount, address caller ); event ShouldRequireClaim(uint256 indexed projectId, bool indexed flag, address caller); event Change( uint256 indexed projectId, IJBToken indexed newToken, IJBToken indexed oldToken, address owner, address caller ); event Transfer( address indexed holder, uint256 indexed projectId, address indexed recipient, uint256 amount, address caller ); function tokenOf(uint256 _projectId) external view returns (IJBToken); function projectOf(IJBToken _token) external view returns (uint256); function projects() external view returns (IJBProjects); function unclaimedBalanceOf(address _holder, uint256 _projectId) external view returns (uint256); function unclaimedTotalSupplyOf(uint256 _projectId) external view returns (uint256); function totalSupplyOf(uint256 _projectId) external view returns (uint256); function balanceOf(address _holder, uint256 _projectId) external view returns (uint256 _result); function requireClaimFor(uint256 _projectId) external view returns (bool); function issueFor( uint256 _projectId, string calldata _name, string calldata _symbol ) external returns (IJBToken token); function changeFor( uint256 _projectId, IJBToken _token, address _newOwner ) external returns (IJBToken oldToken); function burnFrom( address _holder, uint256 _projectId, uint256 _amount, bool _preferClaimedTokens ) external; function mintFor( address _holder, uint256 _projectId, uint256 _amount, bool _preferClaimedTokens ) external; function shouldRequireClaimingFor(uint256 _projectId, bool _flag) external; function claimFor( address _holder, uint256 _projectId, uint256 _amount ) external; function transferFrom( address _holder, uint256 _projectId, address _recipient, uint256 _amount ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IJBTokenUriResolver { function getUri(uint256 _projectId) external view returns (string memory tokenUri); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; library JBOperations { uint256 public constant RECONFIGURE = 1; uint256 public constant REDEEM = 2; uint256 public constant MIGRATE_CONTROLLER = 3; uint256 public constant MIGRATE_TERMINAL = 4; uint256 public constant PROCESS_FEES = 5; uint256 public constant SET_METADATA = 6; uint256 public constant ISSUE = 7; uint256 public constant CHANGE_TOKEN = 8; uint256 public constant MINT = 9; uint256 public constant BURN = 10; uint256 public constant CLAIM = 11; uint256 public constant TRANSFER = 12; uint256 public constant REQUIRE_CLAIM = 13; uint256 public constant SET_CONTROLLER = 14; uint256 public constant SET_TERMINALS = 15; uint256 public constant SET_PRIMARY_TERMINAL = 16; uint256 public constant USE_ALLOWANCE = 17; uint256 public constant SET_SPLITS = 18; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; library JBSplitsGroups { uint256 public constant ETH_PAYOUT = 1; uint256 public constant RESERVED_TOKENS = 2; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './JBTokenAmount.sol'; struct JBDidPayData { // The address from which the payment originated. address payer; // The ID of the project for which the payment was made. uint256 projectId; // The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount. JBTokenAmount amount; // The number of project tokens minted for the beneficiary. uint256 projectTokenCount; // The address to which the tokens were minted. address beneficiary; // The memo that is being emitted alongside the payment. string memo; // Metadata to send to the delegate. bytes metadata; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './JBTokenAmount.sol'; struct JBDidRedeemData { // The holder of the tokens being redeemed. address holder; // The project to which the redeemed tokens are associated. uint256 projectId; // The number of project tokens being redeemed. uint256 projectTokenCount; // The reclaimed amount. Includes the token being paid, the value, the number of decimals included, and the currency of the amount. JBTokenAmount reclaimedAmount; // The address to which the reclaimed amount will be sent. address payable beneficiary; // The memo that is being emitted alongside the redemption. string memo; // Metadata to send to the delegate. bytes metadata; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBPaymentTerminal.sol'; struct JBFundAccessConstraints { // The terminal within which the distribution limit and the overflow allowance applies. IJBPaymentTerminal terminal; // The token for which the fund access constraints apply. address token; // The amount of the distribution limit, as a fixed point number with the same number of decimals as the terminal within which the limit applies. uint256 distributionLimit; // The currency of the distribution limit. uint256 distributionLimitCurrency; // The amount of the allowance, as a fixed point number with the same number of decimals as the terminal within which the allowance applies. uint256 overflowAllowance; // The currency of the overflow allowance. uint256 overflowAllowanceCurrency; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBFundingCycleBallot.sol'; struct JBFundingCycle { // The funding cycle number for each project. // Each funding cycle has a number that is an increment of the cycle that directly preceded it. // Each project's first funding cycle has a number of 1. uint256 number; // The timestamp when the parameters for this funding cycle were configured. // This value will stay the same for subsequent funding cycles that roll over from an originally configured cycle. uint256 configuration; // The `configuration` of the funding cycle that was active when this cycle was created. uint256 basedOn; // The timestamp marking the moment from which the funding cycle is considered active. // It is a unix timestamp measured in seconds. uint256 start; // The number of seconds the funding cycle lasts for, after which a new funding cycle will start. // A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties. // If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle. // If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`. uint256 duration; // A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on. // For example, payment terminals can use this to determine how many tokens should be minted when a payment is received. uint256 weight; // A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`. // If it's 0, each funding cycle will have equal weight. // If the number is 90%, the next funding cycle will have a 10% smaller weight. // This weight is out of `JBConstants.MAX_DISCOUNT_RATE`. uint256 discountRate; // An address of a contract that says whether a proposed reconfiguration should be accepted or rejected. // It can be used to create rules around how a project owner can change funding cycle parameters over time. IJBFundingCycleBallot ballot; // Extra data that can be associated with a funding cycle. uint256 metadata; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBFundingCycleBallot.sol'; struct JBFundingCycleData { // The number of seconds the funding cycle lasts for, after which a new funding cycle will start. // A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties. // If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle. // If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`. uint256 duration; // A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on. // For example, payment terminals can use this to determine how many tokens should be minted when a payment is received. uint256 weight; // A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`. // If it's 0, each funding cycle will have equal weight. // If the number is 90%, the next funding cycle will have a 10% smaller weight. // This weight is out of `JBConstants.MAX_DISCOUNT_RATE`. uint256 discountRate; // An address of a contract that says whether a proposed reconfiguration should be accepted or rejected. // It can be used to create rules around how a project owner can change funding cycle parameters over time. IJBFundingCycleBallot ballot; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBFundingCycleDataSource.sol'; struct JBFundingCycleMetadata { // The reserved rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_RESERVED_RATE`. uint256 reservedRate; // The redemption rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`. uint256 redemptionRate; // The redemption rate to use during an active ballot of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`. uint256 ballotRedemptionRate; // If the pay functionality should be paused during the funding cycle. bool pausePay; // If the distribute functionality should be paused during the funding cycle. bool pauseDistributions; // If the redeem functionality should be paused during the funding cycle. bool pauseRedeem; // If the burn functionality should be paused during the funding cycle. bool pauseBurn; // If the mint functionality should be allowed during the funding cycle. bool allowMinting; // If changing tokens should be allowed during this funding cycle. bool allowChangeToken; // If migrating terminals should be allowed during this funding cycle. bool allowTerminalMigration; // If migrating controllers should be allowed during this funding cycle. bool allowControllerMigration; // If setting terminals should be allowed during this funding cycle. bool allowSetTerminals; // If setting a new controller should be allowed during this funding cycle. bool allowSetController; // If fees should be held during this funding cycle. bool holdFees; // If redemptions should use the project's balance held in all terminals instead of the project's local terminal balance from which the redemption is being fulfilled. bool useTotalOverflowForRedemptions; // If the data source should be used for pay transactions during this funding cycle. bool useDataSourceForPay; // If the data source should be used for redeem transactions during this funding cycle. bool useDataSourceForRedeem; // The data source to use during this funding cycle. IJBFundingCycleDataSource dataSource; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './JBSplit.sol'; import '../libraries/JBSplitsGroups.sol'; struct JBGroupedSplits { // The group indentifier. uint256 group; // The splits to associate with the group. JBSplit[] splits; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; struct JBOperatorData { // The address of the operator. address operator; // The domain within which the operator is being given permissions. // A domain of 0 is a wildcard domain, which gives an operator access to all domains. uint256 domain; // The indexes of the permissions the operator is being given. uint256[] permissionIndexes; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBPaymentTerminal.sol'; import './JBTokenAmount.sol'; struct JBPayParamsData { // The terminal that is facilitating the payment. IJBPaymentTerminal terminal; // The address from which the payment originated. address payer; // The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount. JBTokenAmount amount; // The ID of the project being paid. uint256 projectId; // The weight of the funding cycle during which the payment is being made. uint256 weight; // The reserved rate of the funding cycle during which the payment is being made. uint256 reservedRate; // The memo that was sent alongside the payment. string memo; // Arbitrary metadata provided by the payer. bytes metadata; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; struct JBProjectMetadata { // Metadata content. string content; // The domain within which the metadata applies. uint256 domain; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBPaymentTerminal.sol'; struct JBRedeemParamsData { // The terminal that is facilitating the redemption. IJBPaymentTerminal terminal; // The holder of the tokens being redeemed. address holder; // The ID of the project whos tokens are being redeemed. uint256 projectId; // The proposed number of tokens being redeemed, as a fixed point number with 18 decimals. uint256 tokenCount; // The total supply of tokens used in the calculation, as a fixed point number with 18 decimals. uint256 totalSupply; // The amount of overflow used in the reclaim amount calculation. uint256 overflow; // The number of decimals included in the reclaim amount fixed point number. uint256 decimals; // The currency that the reclaim amount is expected to be in terms of. uint256 currency; // The amount that should be reclaimed by the redeemer using the protocol's standard bonding curve redemption formula. uint256 reclaimAmount; // If overflow across all of a project's terminals is being used when making redemptions. bool useTotalOverflow; // The redemption rate of the funding cycle during which the redemption is being made. uint256 redemptionRate; // The ballot redemption rate of the funding cycle during which the redemption is being made. uint256 ballotRedemptionRate; // The proposed memo that is being emitted alongside the redemption. string memo; // Arbitrary metadata provided by the redeemer. bytes metadata; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './../interfaces/IJBSplitAllocator.sol'; struct JBSplit { // A flag that only has effect if a projectId is also specified, and the project has a token contract attached. // If so, this flag indicates if the tokens that result from making a payment to the project should be delivered claimed into the beneficiary's wallet, or unclaimed to save gas. bool preferClaimed; // A flag indicating if a distribution to a project should prefer triggering it's addToBalance function instead of its pay function. bool preferAddToBalance; // The percent of the whole group that this split occupies. This number is out of `JBConstants.SPLITS_TOTAL_PERCENT`. uint256 percent; // If an allocator is not set but a projectId is set, funds will be sent to the protocol treasury belonging to the project who's ID is specified. // Resulting tokens will be routed to the beneficiary with the claimed token preference respected. uint256 projectId; // The role the of the beneficary depends on whether or not projectId is specified, and whether or not an allocator is specified. // If allocator is set, the beneficiary will be forwarded to the allocator for it to use. // If allocator is not set but projectId is set, the beneficiary is the address to which the project's tokens will be sent that result from a payment to it. // If neither allocator or projectId are set, the beneficiary is where the funds from the split will be sent. address payable beneficiary; // Specifies if the split should be unchangeable until the specified time, with the exception of extending the locked period. uint256 lockedUntil; // If an allocator is specified, funds will be sent to the allocator contract along with all properties of this split. IJBSplitAllocator allocator; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import './JBSplit.sol'; import './JBTokenAmount.sol'; struct JBSplitAllocationData { // The token being sent to the split allocator. address token; // The amount being sent to the split allocator, as a fixed point number. uint256 amount; // The number of decimals in the amount. uint256 decimals; // The project to which the split belongs. uint256 projectId; // The group to which the split belongs. uint256 group; // The split that caused the allocation. JBSplit split; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; struct JBTokenAmount { // The token the payment was made in. address token; // The amount of tokens that was paid, as a fixed point number. uint256 value; // The number of decimals included in the value fixed point number. uint256 decimals; // The expected currency of the value. uint256 currency; }
* @dev Must return the voting units held by an account./ SPDX-License-Identifier: MIT OpenZeppelin Contracts (last updated v4.5.0-rc.0) (token/ERC721/ERC721.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; function _getVotingUnits(address) internal virtual returns (uint256); } pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { _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: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 _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 {} }
634,772
[ 1, 10136, 327, 326, 331, 17128, 4971, 15770, 635, 392, 2236, 18, 19, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 3502, 62, 881, 84, 292, 267, 30131, 261, 2722, 3526, 331, 24, 18, 25, 18, 20, 17, 1310, 18, 20, 13, 261, 2316, 19, 654, 39, 27, 5340, 19, 654, 39, 27, 5340, 18, 18281, 13, 326, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 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, 445, 389, 588, 58, 17128, 7537, 12, 2867, 13, 2713, 5024, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 5666, 25165, 45, 654, 39, 27, 5340, 18, 18281, 14432, 203, 5666, 25165, 45, 654, 39, 27, 5340, 12952, 18, 18281, 14432, 203, 5666, 25165, 9489, 19, 45, 654, 39, 27, 5340, 2277, 18, 18281, 14432, 203, 5666, 315, 16644, 5471, 19, 1887, 18, 18281, 14432, 203, 5666, 315, 16644, 5471, 19, 1042, 18, 18281, 14432, 203, 5666, 315, 16644, 5471, 19, 7957, 18, 18281, 14432, 203, 5666, 315, 16644, 5471, 19, 474, 26362, 19, 654, 39, 28275, 18, 18281, 14432, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 2 ]
./full_match/3/0xEF13EBbB33E3Aeb1aD312A6DAb4Ac2a929C7f23F/sources/Users/kstasi/Documents/work/dANT/contracts/GnosisMultisig.sol
@title Multisignature wallet - Allows multiple parties to agree on transactions before execution. @author Stefan George - <[email protected]>
contract MultiSigWallet { event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); uint256 public constant MAX_OWNER_COUNT = 50; mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(address => bool)) public confirmations; mapping(address => bool) public isOwner; address[] public owners; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint256 transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint256 transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint256 transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint256 transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint256 ownerCount, uint256 _required) { require( ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0 ); _; } receive() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } public validRequirement(_owners.length, _required) constructor(address[] memory _owners, uint256 _required) { for (uint256 i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } { for (uint256 i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.pop(); if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.pop(); if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint256 i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint256 i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } function submitTransaction( address destination, uint256 value, bytes memory data ) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } function confirmTransaction(uint256 transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } function revokeConfirmation(uint256 transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } function executeTransaction(uint256 transactionId) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if ( external_call( txn.destination, txn.value, txn.data.length, txn.data ) ) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } function executeTransaction(uint256 transactionId) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if ( external_call( txn.destination, txn.value, txn.data.length, txn.data ) ) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } function executeTransaction(uint256 transactionId) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if ( external_call( txn.destination, txn.value, txn.data.length, txn.data ) ) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } function external_call( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; assembly { result := call( destination, value, d, x, ) } return result; } function external_call( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; assembly { result := call( destination, value, d, x, ) } return result; } function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } function addTransaction( address destination, uint256 value, bytes memory data ) internal virtual notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } function addTransaction( address destination, uint256 value, bytes memory data ) internal virtual notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } function getTransactionCount(bool pending, bool executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) if ( (pending && !transactions[i].executed) || (executed && transactions[i].executed) ) count += 1; } function getOwners() public view returns (address[] memory) { return owners; } function getConfirmations(uint256 transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } function getConfirmations(uint256 transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory _transactionIds) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) if ( (pending && !transactions[i].executed) || (executed && transactions[i].executed) ) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory _transactionIds) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) if ( (pending && !transactions[i].executed) || (executed && transactions[i].executed) ) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
8,270,265
[ 1, 5049, 291, 724, 1231, 9230, 300, 25619, 3229, 1087, 606, 358, 1737, 992, 603, 8938, 1865, 4588, 18, 225, 7780, 74, 304, 15391, 280, 908, 300, 411, 334, 10241, 304, 18, 908, 280, 908, 36, 8559, 773, 1900, 18, 2758, 34, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 5991, 8267, 16936, 288, 203, 565, 871, 17580, 367, 12, 2867, 8808, 5793, 16, 2254, 5034, 8808, 24112, 1769, 203, 565, 871, 14477, 4431, 12, 2867, 8808, 5793, 16, 2254, 5034, 8808, 24112, 1769, 203, 565, 871, 2592, 3951, 12, 11890, 5034, 8808, 24112, 1769, 203, 565, 871, 8687, 12, 11890, 5034, 8808, 24112, 1769, 203, 565, 871, 8687, 5247, 12, 11890, 5034, 8808, 24112, 1769, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 5793, 16, 2254, 5034, 460, 1769, 203, 565, 871, 16837, 30296, 12, 2867, 8808, 3410, 1769, 203, 565, 871, 16837, 24543, 12, 2867, 8808, 3410, 1769, 203, 565, 871, 30813, 3043, 12, 11890, 5034, 1931, 1769, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 29602, 67, 7240, 273, 6437, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 5947, 13, 1071, 8938, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 6932, 1012, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 353, 5541, 31, 203, 565, 1758, 8526, 1071, 25937, 31, 203, 565, 2254, 5034, 1071, 1931, 31, 203, 565, 2254, 5034, 1071, 2492, 1380, 31, 203, 203, 565, 1958, 5947, 288, 203, 3639, 1758, 2929, 31, 203, 3639, 2254, 5034, 460, 31, 203, 3639, 1731, 501, 31, 203, 3639, 1426, 7120, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 16936, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 3410, 15264, 2 ]
./full_match/5/0xc2166567dbCC8Bc35ce79Ed429D75451AfC14985/sources/localhost/contracts/GatebridgeV2Factory.sol
require(resourceId != address(0), 'GatebridgeV2: ZERO_ADDRESS');
function createPool(bytes32 resourceId, uint _chainId) external override returns (address pool) { bytes memory bytecode = type(GatebridgeV2LPToken).creationCode; bytes32 salt = keccak256(abi.encodePacked(resourceId)); assembly { pool := create2(0, add(bytecode, 32), mload(bytecode), salt) } getPool[resourceId][_chainId] = pool; getResourceId[_chainId][pool] = resourceId; emit PoolCreated(resourceId, _chainId, pool, allPools.length); }
1,852,306
[ 1, 6528, 12, 3146, 548, 480, 1758, 12, 20, 3631, 296, 13215, 18337, 58, 22, 30, 18449, 67, 15140, 8284, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 2864, 12, 3890, 1578, 15035, 16, 2254, 389, 5639, 548, 13, 3903, 3849, 1135, 261, 2867, 2845, 13, 288, 203, 3639, 1731, 3778, 22801, 273, 618, 12, 13215, 18337, 58, 22, 14461, 1345, 2934, 17169, 1085, 31, 203, 3639, 1731, 1578, 4286, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3146, 548, 10019, 203, 3639, 19931, 288, 203, 5411, 2845, 519, 752, 22, 12, 20, 16, 527, 12, 1637, 16651, 16, 3847, 3631, 312, 945, 12, 1637, 16651, 3631, 4286, 13, 203, 3639, 289, 203, 3639, 28575, 63, 3146, 548, 6362, 67, 5639, 548, 65, 273, 2845, 31, 203, 3639, 5070, 548, 63, 67, 5639, 548, 6362, 6011, 65, 273, 15035, 31, 203, 203, 3639, 3626, 8828, 6119, 12, 3146, 548, 16, 389, 5639, 548, 16, 2845, 16, 777, 16639, 18, 2469, 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 ]
./partial_match/3/0x3d85dF677bB60B3401F4e59c99087B611c07D007/sources/YIN.sol
Return data is optional
if (returndata.length > 0) {
5,208,329
[ 1, 990, 501, 353, 3129, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13491, 309, 261, 2463, 892, 18, 2469, 405, 374, 13, 288, 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 ]